如何在Django的Admin中检查FileField是否被修改?

发布于 2024-08-09 14:26:34 字数 1030 浏览 4 评论 0原文

我正在尝试使用不应修改的文件创建一个模型。但文件的注释是可以的。

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

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

I am trying to do a model with a file that shouldn't be modified. But the comment of the file can be.

Here is what I did, but we cannot modify the comment.
How can I test if a new file (using the browse button) as been sent and in this case only, create a new instance of the model ? If no upload of a new file, 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())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

筱果果 2024-08-16 14:26:34
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
     """
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
     """
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文