慕碼人8056858
2022-11-01 14:31:35
我們在我們的網站中使用帶有 Crispy 表單的 Django。我有一個由{% 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, })但問題是,當我從瀏覽器上傳文件時,我收到一條錯誤消息“沒有提交文件。請檢查表單上的編碼類型?!?并且該文件未保存。表單的編碼類型不正確。如何使用 Crispy 表單更改編碼類型?
1 回答

不負相思意
TA貢獻1777條經驗 獲得超10個贊
我在 GitHub 上提交了一個問題,并向與我一起工作的開發人員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在網站上的其他問題中找到文檔。
添加回答
舉報
0/150
提交
取消