Django Admin - 与主要模型一起验证内联

And*_*rea 4 django validation django-admin

我有一个非常复杂的验证要求,我无法让Django管理员满足它.

我有一个主模型(django.contrib.auth.models.User)和几个看起来像的模型

class SomeProfile(models.Model):
    user = models.OneToOneField(User)
    # more fields
Run Code Online (Sandbox Code Playgroud)

我想检查一下,如果用户属于某个组,则它具有相应的配置文件.因此,如果用户在组中,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)
Run Code Online (Sandbox Code Playgroud)

我的问题是,UserAdminForm.clean()我无法访问内联中发布的数据.所以我可以通过检查判断用户是否在Foo组中self.cleaned_data['groups'],但我无法判断是否FooProfile已传输.

如何检查此验证要求?

编辑:

我试着更好地解释这个问题,因为答案中存在误解.

我创建新用户时遇到问题.事实是,配置文件是强制性的(根据组).假设管理员创建了一个新用户; 然后我必须在各种GroupProfiles的管理表单中添加内联.

如何检查正确的配置文件是否为空?我不能使用模型的clean()方法User,因为在那里我无法检查用户属于哪些组:它尚未创建.

我只能clean()在表单方法中访问有关组的信息- 但是我没有关于配置文件的信息,因为这些信息是内联提交的.

sac*_*che 7

1

好吧,我一直在环顾四周,所有这些东西是如何工作的,我在这里发现了一个非常相似的问题.

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
Run Code Online (Sandbox Code Playgroud)