Django与请求用户一起进行独特的验证

时间:2018-01-14 14:57:25

标签: django

在Django中,我需要验证unique_togetherauthor字段title。 问题是authorrequest.user,那么验证管理表单的最佳方法是什么? 我有这个管理员:

@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):

    exclude = ('author',)

    def save_model(self, request, obj, form, change):
        """Save ``author`` as request user."""
        if getattr(obj, 'author', None) is None:
            obj.author = request.user
        super().save_model(request, obj, form, change)

我可以在save_model()内查询并过滤authortitle,但这并不是很有效。 我还尝试使用forms.ModelForm,但我无法在request.user方法中获得clean()

这是我的模特:

class Document(models.Model):

    title = models.CharField(max_length=32, blank=True)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE
    )

    class Meta:
        unique_together = (('title', 'author'),)

谢谢。

2 个答案:

答案 0 :(得分:0)

在模型上加上unique_together约束

class Foo(models.Model):
    field_1 = models.CharField(max_length=50)
    field_2 = models.CharField(max_length=50)

    class Meta:
        unique_together = ('field_1', 'field_2')

Django将自动为您进行验证,如果失败则会抛出IntegrityError(来自django.db import IntegrityError)

答案 1 :(得分:0)

无法从管理员中排除author字段。解决方案是使用author方法隐藏get_form。如果有人试图更改隐藏的输入值,save_model方法仍然有用。

@admin.register(Document)
class DocumentAdmin(admin.ModelAdmin):

    # exclude = ('author',)

    def get_readonly_fields(self, request, obj=None):
        """Make ``author`` field readonly on update."""
        return ['author'] if obj else []

    def get_form(self, request, obj=None, **kwargs):
        """Hide ``author`` selection default to request user on create."""
        form = super().get_form(request, obj, **kwargs)
        if not obj:
            form.base_fields['author'].initial = request.user
            form.base_fields['author'].widget = forms.HiddenInput()
        return form

    def save_model(self, request, obj, form, change):
        """Save ``author`` field as request user on create."""
        if getattr(obj, 'author') != request.user and not change:
            obj.author = request.user
        super().save_model(request, obj, form, change)