我有一个相当复杂的验证要求,我无法让 Django admin 来满足它。
我有一个主模型( django.contrib.auth.models.User
)和几个看起来像的模型
class SomeProfile(models.Model):
user = models.OneToOneField(User)
# more fields
我想检查一下,如果用户属于某个组,则它具有相应的配置文件。因此,如果用户在组 Foo
中他应该有一个非空 FooProfile
.
我应该把这个验证规则放在哪里?我无法将其放入模型中。事实上,验证表单时尚未创建用户,因此我无法访问他的组。所以我需要求助于表单验证。这是我写的:
class UserAdminForm(forms.ModelForm):
"""
A custom form to add validation rules which cannot live in the
model. We check that users belonging to various groups actually
have the corresponding profiles.
"""
class Meta:
model = User
def clean(self):
# Here is where I would like to put the validation
class FooInline(admin.TabularInline):
model = FooProfile
max_num = 1
class UserAdmin(admin.ModelAdmin):
model = User
form = UserAdminForm
inlines = [FooInline]
admin.site.register(User, UserAdmin)
我的问题是在UserAdminForm.clean()
里面我无权访问内嵌中发布的数据。所以我可以通过检查 self.cleaned_data['groups']
来判断用户是否在 Foo 组中,但我无法判断是否 FooProfile
已传送。
How do I check this validation requirement?
编辑:
我尝试更好地解释这个问题,因为答案中存在误解。
创建新用户时遇到问题。事实上,配置文件是强制性的(根据组)。假设管理员创建了一个新用户;然后我必须在管理表单中为各种 GroupProfile 添加内联。
如何检查正确的配置文件不为空?我无法使用 clean()
User
的方法模型,因为在那里我无法检查用户所属的组:它尚未创建。
我只能访问 clean()
中的群组信息表单的方法 - 但我没有有关配置文件的信息,因为此信息是通过内联提交的。
最佳答案
1
好吧,我一直在环顾四周,所有这些东西是如何工作的,我发现一个非常相似的问题 here .
2
有一种方法可以同时获取所有数据,也许您可以找到问题的答案
class UserAdminForm(forms.ModelForm):
"""
A custom form to add validation rules which cannot live in the
model. We check that users belonging to various groups actually
have the corresponding profiles.
"""
class Meta:
model = User
def clean(self):
self.data # <--here is all the data of the request
self.data['groups']
self.data['profile_set-0-comments'] # some field
# some validations
return self.cleaned_data
关于Django Admin - 与主模型一起验证内联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6681464/