How can I check if a FileField has been changed in the Admin of Django?

I am trying to make a model with a file that should not be modified. But the file comment can be.

Here's what I did, but we can't change the comment. How can I check if a new file has been submitted (using the browse button) and only then create a new instance of the model? If you are not uploading a new file, please update the comment.

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())

      

+2


source to share


1 answer


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
     """

      



+7


source







All Articles