<div class="modal fade" id="modal-add-family">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">添加家系</h4>
</div>
<div class="modal-body">
<div class="box-body">
<form class="form-horizontal" action="/app/add_family/" method="post"
enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="col-sm-2 control-label">编号</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="number"
placeholder="系统编号">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">家系名称</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name" required="required"
placeholder="家系名称">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">家系图</label>
<div class="col-sm-10">
<input type="file" class="form-control" name="file" required="required">
<p class="help-block">请点击按钮上传家系图</p>
</div>
</div>
<input type="submit" value="Submit" class="hidden" id="add_submit"/>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
<button type="submit" class="btn btn-primary" id="add_item">添加</button>
</div>
</div>
</div>
</div>
后台接收:
@require_POST
@login_required(login_url='/app/login')
def add(request):
number = request.POST.get("number", None)
name = request.POST.get("name", None)
file = request.FILES.get("file", None)
if not name or not file:
message = "请完善上传信息"
else:
try:
family = Family(number=number, name=name, image=file)
family.save()
message = "添加家系成功!"
except:
message = "添加家系失败!"
s = SampleList()
return s.get(request, message=message)
Model:
def family_directory_path(instance, filename):
maxid = max(obj.id for obj in FilePath.objects.all())
prefix = FilePath.objects.get(id=maxid).path
return '{0}/family/{1}/{2}'.format(prefix, instance.pk, filename)
class Family(Base):
class Meta:
verbose_name = '家系信息'
verbose_name_plural = '家系信息'
def __str__(self):
return f'{self.pk} - {self.name}'
def natural_key(self):
return self.name
number = models.CharField(max_length=64, blank=True, null=True, verbose_name='编号')
name = models.CharField(max_length=64, blank=True, null=True, verbose_name='名称')
image = models.ImageField(upload_to=family_directory_path, blank=True, null=True, verbose_name='家系图')
family_disease = models.ForeignKey(FamilyDisease, blank=True, on_delete=models.SET_NULL, null=True, verbose_name='家族病史')
family_disease_abstract = models.TextField(blank=True,null=True,verbose_name='家族病史描述')
注意点-- <form enctype="multipart/form-data">
这里一定要写, 否则提交的只是文件名, 而且不在 FILES 里面 而是放在了 POST 里面
网友评论