我们在网站上将Django与Crispy表单结合使用。我有一个由{% crispy form %}
呈现的表格。这是形式的代码:
class ProfileForm(AddAttributesToFieldsMixin, CleanDateOfBirthMixin, LocalizedFirstLastNameMixin, forms.ModelForm):
profile_picture = forms.ImageField(required=False, widget=CustomPhotoWidget, label=_('Update your profile picture'), error_messages={'required': _("A profile picture is required.")})
class Meta:
model = User
fields = ('slug', 'gender', 'date_of_birth', 'profile_picture')
表单使用CustomPhotoWidget
,其定义如下:
class CustomPhotoWidget(forms.widgets.Widget):
def render(self, name, value, attrs=None, renderer=None):
return render_to_string(template_name='accounts/edit_profile/widgets/photo_widget.html', context={
'name': name,
'user_photo': self.attrs['user'].photo,
})
但是问题是,当我从浏览器上载文件时,收到错误消息“未提交文件。请检查表单上的编码类型。”并且文件未保存。表单的编码类型不正确。如何使用脆皮形式更改编码类型?
[我在GitHub上提交了issue,并向与我合作的开发人员Aaron Chong寻求帮助。他检查并发现了问题。 CustomPhotoWidget
应该这样定义:
class CustomPhotoWidget(forms.widgets.Widget):
needs_multipart_form = True
def render(self, name, value, attrs=None, renderer=None):
return render_to_string(template_name='accounts/edit_profile/widgets/photo_widget.html', context={
'name': name,
'user_photo': self.attrs['user'].photo,
})
needs_multipart_form = True
是修复表格的编码类型所需要的。我将此解决方案上传到Stack Overflow,因为我没有在网站上的其他问题中找到needs_multipart_form
。