我在Django中有这样的表单:
class ProfessionalForm(forms.ModelForm):
name = forms.CharField(required=True, label=_("name").title())
email = forms.EmailField(required=True)
avatar = forms.FileField(required=False, label=_("avatar").title())
front_document = forms.FileField(required=False, label=_("front document").title())
back_document = forms.FileField(required=False, label=_("back document").title())
class Meta:
model = Professional
fields = ("name", "email", "avatar", "front_document", "back_document")
问题是:在页面中,我放了一个文件(例如,“头像”)并保存,一切正常。因此,当我再次在页面中输入并设置另一个文件(例如“ front_document”)时,控制器将丢失对“ avatar”的引用,并将此字段设置为空。发生什么事了?
我的views.py
def myprofile(request):
if request.method == "POST":
form = ProfessionalForm(request.POST, request.FILES)
if form.is_valid():
professional = form.save(commit=False)
professional.user = request.user
professional.save()
request.session['professional_avatar_url'] = \
professional.avatar.url if professional.avatar else settings.NO_IMAGE
else:
professional_t = Professional \
.objects \
.get_or_create(user=request.user,
defaults={'name': request.user.first_name + " " + request.user.last_name,
'email': request.user.email})
professional = professional_t[0]
return redirect('myprofile')
else:
professional_t = Professional\
.objects\
.get_or_create(user=request.user,
defaults={'name':request.user.first_name + " " + request.user.last_name,
'email':request.user.email})
professional = professional_t[0]
form = ProfessionalForm(
instance=professional)
return render(request, 'npadmin/myprofile.html', {'form':form, 'professional':professional})
还有我的html:
<form method="post" action="{% url 'myprofile' %}"
class="form-horizontal" role="form"
enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form-group row">
<label class="col-2 col-form-label">{{ field.label_tag }}</label>
<div class="col-10">
{% render_field field class+="form-control" %}
{% if field.errors %}
<br/>
{% for error in field.errors %}
<div class="alert alert-danger alert-dismissable">
<p><strong>{{ error|escape }}</strong></p>
</div>
{% endfor %}
{% endif %}
</div>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
<input type="submit" value="{% trans 'save' %}" >
</form>
我使用Python 3.6和Django 2.0