Django 如何从管理中排除模型表单验证
我需要,如果用户没有选择字段Django 如何从管理中排除模型表单验证,django,python-3.x,Django,Python 3.x,我需要,如果用户没有选择字段acc\u type,用户将不会继续注册。因此,我在modelblank=False中编写了代码。但问题是当superuser在登录后更新其信息时,用户表单会保留superuser以填充该字段。因此,我希望对于超级用户、stuff或管理员类型的用户,应排除某些字段的验证。请参见屏幕截图: 我在模型中所做的: 型号.py class Ext_User(AbstractUser): email = models.EmailField(unique=True)
acc\u type
,用户将不会继续注册。因此,我在modelblank=False
中编写了代码。但问题是当superuser
在登录后更新其信息时,用户表单会保留superuser
以填充该字段。因此,我希望对于超级用户
、stuff
或管理员类型的用户,应排除某些字段的验证。请参见屏幕截图:
我在模型中所做的:
型号.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)
您的做法是错误的-您希望在模型中允许空白,并覆盖公共视图(而不是管理视图)中使用的模型表单以禁止它: 型号:
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 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)
# make the field required for the public form
self.fields["acc_type"].required = True
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:]
另一个解决方案是添加一个专用的“admin”ACC_类型选项,并将其从公共模型表单的选项中删除,以便最终用户只剩下“member”和“vendor”选项:
型号:
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 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)
# make the field required for the public form
self.fields["acc_type"].required = True
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:]
事实上,我是django的新手。你能给我多一点想法,然后它会帮助我吗?@StreetCoder我编辑了我的帖子,添加了代码示例。这些都是未经测试的,但基于现有的工作代码,所以它们应该只工作(tm)。