仅当在 Django 中选择了新文件时,如何让图像表单字段更新?

How to get an image form field to update only if a new file has been chosen in django?

我有一个带有图像字段的自定义个人资料表单,用户可以在其中上传个人资料图片以及其他一些字段。到目前为止它工作正常。问题是,当提交表单时,它总是上传和更新字段,即使用户没有选择文件。因此,用户提交了表单并上传了图片。 He/she 然后稍后回来更新其他字段,但不更新图片。提交表单后,个人资料图片消失并重置为默认值。如何让图像字段仅在选择了新文件时更新?

modesl.py

class Profil(models.Model):
    def content_file_userpic(instance, filename):
        return '/'.join(['pics', instance.user.username, filename])

    user = models.OneToOneField(User, primary_key=True)
    user_pic = models.ImageField(upload_to=content_file_userpic, blank=True, verbose_name='Foto', default='user_pic_default.png')

forms.py

class ProfilForm(ModelForm):
    user_pic = forms.ImageField(label='Foto',required=False, widget=forms.FileInput)

您忘记向表单构造函数添加 instance 参数:

profile = Profil.objects.get(user=request.user)
form = ProfilForm(request.POST, request.FILES, instance=profile)