如何检查是否已在Django管理员中修改了FileField?

时间:2009-10-27 03:50:50

标签: python django django-admin django-forms django-file-upload

我正在尝试使用不应修改的文件来创建模型。但该文件的评论可以是。

这是我所做的,但我们无法修改评论。 如何测试是否已发送新文件(使用浏览按钮),仅在此情况下,创建模型的新实例?如果没有上传新文件,请更新评论。

admin.py

class CGUAdminForm(forms.ModelForm):
    class Meta:
        model = ConditionsUtilisation

    def clean_file(self):
        if self.instance and self.instance.pk is not None:
            raise forms.ValidationError(_(u'You cannot modify the file. Thank you to create a new instance.'))
        # do something that validates your data
        return self.cleaned_data["file"]

class CGUAdmin(admin.ModelAdmin):
    form = CGUAdminForm

admin.site.register(ConditionsUtilisation, CGUAdmin)

models.py

class ConditionsUtilisation(models.Model):
    date = models.DateField(_(u'Date d\'upload'), editable=False, auto_now_add=True)
    comment = models.TextField(_(u'Commentaire de modification'))
    file = models.FileField(_(u'CGU'), upload_to='subscription/cgu/', storage=CGUFileSystemStorage())

1 个答案:

答案 0 :(得分:7)

if 'file' in form.changed_data:
     """
     File is changed
     """
     raise forms.ValidationError("No, don't change the file because blah blah")
else:
     """
     File is not changed
     """