Python 如何在Django中实现多个角色?
我想做一个管理角色的应用程序,其中一个用户可以有多个角色。我已经创建了两个模型,一个用于角色,另一个用于models.py中的用户。My models.py的外观如下所示:Python 如何在Django中实现多个角色?,python,django,django-models,django-forms,Python,Django,Django Models,Django Forms,我想做一个管理角色的应用程序,其中一个用户可以有多个角色。我已经创建了两个模型,一个用于角色,另一个用于models.py中的用户。My models.py的外观如下所示: class Role(models.Model): DOCTOR = 1 NURSE = 2 DIRECTOR = 3 ENGENEER = 4 ROLE_CHOICES = { (DOCTOR, 'doctor'), (NURSE, 'nurse'),
class Role(models.Model):
DOCTOR = 1
NURSE = 2
DIRECTOR = 3
ENGENEER = 4
ROLE_CHOICES = {
(DOCTOR, 'doctor'),
(NURSE, 'nurse'),
(DIRECTOR, 'director'),
(ENGENEER, 'engeneer'),
}
id = models.PositiveIntegerField(choices = ROLE_CHOICES, primary_key = True)
def __str__(self):
return self.get_id_display()
class User(AbstractUser):
roles = models.ManyToManyField(Role)
class UserCreationForm(UserCreationForm):
fields = ('username', 'password1', 'password2')
model = User
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].label = 'Insert username'
self.fields['password1'].label = 'Insert password'
self.fields['password2'].label = 'Again'
class RoleCreationForm(forms.ModelForm):
class Meta:
model = Role
fields = ('id',)
class UserCreateView(CreateView):
model = User
form_class = forms.UserCreationForm
template_name = 'user_form.html'
redirect_field_name = 'index.html'
success_url = reverse_lazy('accounts:index')
class RoleCreateView(CreateView):
model = Role
form_class = forms.RoleCreationForm
template_name = 'role_form.html'
redirect_field_name = 'index.html'
success_url = reverse_lazy('accounts:index')
现在我要做的是从用户表单中建立角色。我的forms.py如下所示:
class Role(models.Model):
DOCTOR = 1
NURSE = 2
DIRECTOR = 3
ENGENEER = 4
ROLE_CHOICES = {
(DOCTOR, 'doctor'),
(NURSE, 'nurse'),
(DIRECTOR, 'director'),
(ENGENEER, 'engeneer'),
}
id = models.PositiveIntegerField(choices = ROLE_CHOICES, primary_key = True)
def __str__(self):
return self.get_id_display()
class User(AbstractUser):
roles = models.ManyToManyField(Role)
class UserCreationForm(UserCreationForm):
fields = ('username', 'password1', 'password2')
model = User
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].label = 'Insert username'
self.fields['password1'].label = 'Insert password'
self.fields['password2'].label = 'Again'
class RoleCreationForm(forms.ModelForm):
class Meta:
model = Role
fields = ('id',)
class UserCreateView(CreateView):
model = User
form_class = forms.UserCreationForm
template_name = 'user_form.html'
redirect_field_name = 'index.html'
success_url = reverse_lazy('accounts:index')
class RoleCreateView(CreateView):
model = Role
form_class = forms.RoleCreationForm
template_name = 'role_form.html'
redirect_field_name = 'index.html'
success_url = reverse_lazy('accounts:index')
views.py如下所示:
class Role(models.Model):
DOCTOR = 1
NURSE = 2
DIRECTOR = 3
ENGENEER = 4
ROLE_CHOICES = {
(DOCTOR, 'doctor'),
(NURSE, 'nurse'),
(DIRECTOR, 'director'),
(ENGENEER, 'engeneer'),
}
id = models.PositiveIntegerField(choices = ROLE_CHOICES, primary_key = True)
def __str__(self):
return self.get_id_display()
class User(AbstractUser):
roles = models.ManyToManyField(Role)
class UserCreationForm(UserCreationForm):
fields = ('username', 'password1', 'password2')
model = User
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].label = 'Insert username'
self.fields['password1'].label = 'Insert password'
self.fields['password2'].label = 'Again'
class RoleCreationForm(forms.ModelForm):
class Meta:
model = Role
fields = ('id',)
class UserCreateView(CreateView):
model = User
form_class = forms.UserCreationForm
template_name = 'user_form.html'
redirect_field_name = 'index.html'
success_url = reverse_lazy('accounts:index')
class RoleCreateView(CreateView):
model = Role
form_class = forms.RoleCreationForm
template_name = 'role_form.html'
redirect_field_name = 'index.html'
success_url = reverse_lazy('accounts:index')
如何显示用户表单中的所有角色并从中选择多个角色?我假设您的
UserCreationForm
是表单的子类。ModelForm
也包括:
1) User
型号中没有password1
或password2
字段-仅password
。因此,要确认密码,您必须指定confirm\u password
字段并覆盖clean
方法以检查它们是否相等
2) 要在表单中显示角色
,只需在字段列表中指定“角色”
。由于角色
字段存在于用户
模型中,django将找到正确的小部件,正确显示并验证它
3) 你没有写过,但我猜你添加到了settings.py
?这将把默认的用户
模型更改为您的应用程序模型
4) 您的UserCreateView
将以纯文本形式存储密码,这是一个非常糟糕的主意。阅读有关如何正确存储密码的更多信息
class UserCreationForm(forms.ModelForm):
确认\u password=forms.CharField(widget=forms.PasswordInput())
类元:
字段=(‘用户名’、‘密码’、‘确认密码’、‘角色’)
模型=用户
小部件={
“密码”:forms.PasswordInput(),
“角色”:forms.CheckboxSelectMultiple()
}
定义初始化(self,*args,**kwargs):
super()
self.fields['username'].label='Insert username'
self.fields['password'].label='Insert password'
def清洁(自清洁):
cleaned_data=super().clean()
password=已清理的数据。获取(“密码”)
确认密码=已清理的数据。获取(“确认密码”)
如果输入密码!=确认密码:
raise forms.ValidationError(
“密码和确认密码不匹配”
)
实际上,您可能只想使用OneToOneField
到User
和ManyToManyField
到Role
创建附加模型,而不是覆盖djangoUser
,因为替换djangoUser
模型可能会导致问题
退房。您可以使用子类添加
角色
看起来不像类UserCreationForm(UserCreationForm):
在显示角色选择器的表单中的字段
变量中的角色
属性正确,但为空,我如何解决这个问题?您可以使用django admin填充它们。但是我想显示角色选择器。当我尝试在django admin中创建角色时,它会显示一个选择器,其中包含我在模型中定义的角色,是否有一些方法可以执行相同的操作,但在用户
表单中?是否要直接在表单中动态添加不同的角色?@PaulMiranda我已将表单更新为使用复选框selectmultiple
for角色
字段。它非常简单直观,可以从用户表单中选择多个角色。