在Django中,我需要验证unique_together
和author
字段title
。
问题是author
是request.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()
内查询并过滤author
和title
,但这并不是很有效。
我还尝试使用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'),)
谢谢。
答案 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)