gpt4 book ai didi

python - Django:ModelForms:ImageField 始终为空并被 ModelForm 拒绝

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:11 27 4
gpt4 key购买 nike

我基于几个 ModelForm 元素创建了一个表单。除了图像字段。由于缺少 ImageField form.is_valid() 总是返回 False - 即使我将 request.FILES 传递给表单。

为什么带有 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 设置为:

<form action="{% url 'changeprofile' %}" method="post" enctype="multipart/form-data">

否则 request.FILES 将永远为空。

关于python - Django:ModelForms:ImageField 始终为空并被 ModelForm 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20394802/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com