如何从管理员中排除模型表单验证

时间:2018-12-27 07:51:24

标签: django python-3.x

我需要如果用户未选择字段acc_type,则该用户将不会继续注册。所以我写了模型blank=False。但是问题在于superuser登录后更新他的信息时,用户表单保留superuser来填写该字段。因此,我希望对superuserstuff或管理员类型的用户排除某些字段的验证。请查看屏幕截图:enter image description here

我在模型中所做的:

models.py

class Ext_User(AbstractUser):
    email = models.EmailField(unique=True)
    ACC_TYPE = (
        (1, "Member"),
        (2, "Vendor")
    )
    acc_type = models.IntegerField("Account Type", choices=ACC_TYPE, null=True, blank=False)

1 个答案:

答案 0 :(得分:1)

您正在以错误的方式进行“舍入-您要在此处进行的操作是允许模型中的空白并覆盖公共视图(而非管理员)中使用的ModelForm禁止它:

型号:

class Ext_User(AbstractUser):
    email = models.EmailField(unique=True)
    ACC_TYPE = (
        (1, "Member"),
        (2, "Vendor")
    )
    # Allow blank for the django admin
    acc_type = models.IntegerField("Account Type", choices=ACC_TYPE, null=True, blank=True)

公众视野的形式:

class UserForm(forms.ModelForm):
    class Meta:
        model = Ext_user

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # make the field required for the public form
        self.fields["acc_type"].required = True

另一种解决方案是添加专用的“ admin” ACC_TYPE选择,并将其从公共ModelForm的选择中删除,这样最终用户只剩下“ member”和“ vendor”选择:

型号:

class Ext_User(AbstractUser):
    email = models.EmailField(unique=True)
    ACC_TYPE = (
        (0, "Admin"), # add an 'Admin' choice for the django admin
        (1, "Member"),
        (2, "Vendor")
    )
    acc_type = models.IntegerField("Account Type", choices=ACC_TYPE, null=True, blank=False)

公众视野的形式:

class UserForm(forms.ModelForm):
    class Meta:
        model = Ext_user

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # exclude the 'admin' choice for the public form
        self.fields["acc_type"].choices = Ext_user.ACC_TYPES[1:]