文件未以 Django 形式上传 - 编码类型不正确

Files not uploaded in Django form - encoding type incorrect

我们在我们的网站中使用带有 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,
        })

但问题是,当我从浏览器上传文件时,收到一条错误消息 "No file was submitted. Check the encoding type on the form." 并且文件未保存。表单的编码类型不正确。如何更改脆皮表格的编码类型?

我提交了 issue on GitHub and asked for help from a developer I work with, 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 记录。