本文介绍了Django:ModelForms:ImageField始终为空,并被ModelForm拒绝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我基于几个 ModelForm
元素创建了一个表单.除 ImageField
.由于缺少ImageField,因此即使我将 request.FILES
传递给表单,也始终会返回 False
(错误).
I created a form based on several ModelForm
elements. All fields work fine excluding theImageField
. Due to the missing ImageField form.is_valid()
always returns False
- even though I pass request.FILES
to form.
为什么带有ImageField的表单总是无效/为空?
表格
class UserProfileForm2(forms.ModelForm):
class Meta:
model = models.UserProfile
fields = ['description', 'picture']
class LocationForm(forms.ModelForm):
class Meta:
model = models.Location
fields = ['city', 'state', 'country']
class UserForm(forms.ModelForm):
class Meta:
model = registration_models.User
fields = ['first_name', 'last_name']
模型
class Location(models.Model):
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __unicode__(self):
return ' - '.join([self.city, self.state, self.country])
class UserProfile(models.Model):
authenticationuser = fields.AutoOneToOneField(AuthUser)
description = models.TextField()
picture = models.ImageField(upload_to='uploaded_files/', null=True)
location = models.ForeignKey(Location, null=True)
appear_in_public_ranking = models.BooleanField(default=True)
def __unicode__(self):
return self.authenticationuser.username
查看
@login_required
def changeprofile(request):
form = None
# user posted his new profile settings
if request.method == 'POST':
user_form = myforms.UserForm(request.POST)
user_profile_form = myforms.UserProfileForm2(request.POST, request.FILES)
location_form = myforms.LocationForm(request.POST)
forms_are_invalid = not (user_form.is_valid() and user_profile_form.is_valid() and not location_form.is_valid())
if forms_are_invalid:
forms = {'user_form':user_form,
'user_profile_form':user_profile_form,
'location_form':location_form}
return shortcuts.render(request, 'changeprofile.html', forms)
location_form.save()
user_form.save()
user_profile_form.save()
return HttpResponseRedirect('/profile')
else:
forms = {'user_form':user_form,
'user_profile_form':user_profile_form,
'location_form':location_form}
return shortcuts.render(request, 'changeprofile.html', forms)
模板
<form action="{% url 'changeprofile' %}" method="post">
{% csrf_token %}
{{ user_form }}
{{ location_form }}
{{ user_profile_form }}
<input type="submit" value="Submit" />
</form>
推荐答案
如果表单包含文件输入,则必须在表单中将 enctype
设置为:
If your form contains file input then you must set enctype
in your form as:
<form action="{% url 'changeprofile' %}" method="post" enctype="multipart/form-data">
否则, request.FILES
始终为空.
这篇关于Django:ModelForms:ImageField始终为空,并被ModelForm拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!