【问题标题】:Django Admin - Validating inlines together with main modelsDjango Admin - 与主要模型一起验证内联
【发布时间】:2011-10-04 14:51:14
【问题描述】:

我有一个相当复杂的验证要求,我无法让 Django 管理员满足它。

我有一个主模型 (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

如何检查此验证要求?

编辑:

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

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

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

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

【问题讨论】:

    标签: django django-admin validation


    【解决方案1】:

    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
    

    【讨论】:

    • 我不确定这会如何改变问题。创建新用户时我仍然遇到问题。我已经编辑了答案以更好地解释问题,请看一下。在我看来,将 GroupProfiles 与通用配置文件相关联并不会改变问题,除了使用配置文件模型而不是用户。我仍然不知道如何验证管理员创建的新用户。
    猜你喜欢
    • 1970-01-01
    • 2017-10-26
    • 2012-04-19
    • 2012-11-11
    • 2018-10-11
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多