Django-如何保存所选角色?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django-如何保存所选角色?相关的知识,希望对你有一定的参考价值。
我想在成员添加表单中选择成员的角色。我列出了角色,但是我不知道如何保存所选角色。我该怎么做?我正在等待您的帮助。
forms.py
class CalisanForm(UserCreationForm):
username = forms.CharField(max_length=100, label='Kullanıcı Adı')
email = forms.EmailField(max_length=200, help_text='Required')
password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput)
password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput)
group = forms.ModelChoiceField(queryset=Group.objects.all(), widget=forms.widgets.Radioselect(), empty_label=None)
roles = forms.ModelChoiceField(queryset=GroupMemberRole.objects.all(), widget=forms.widgets.RadioSelect(), empty_label=None)
def __init__(self, *args, **kwargs):
qs = kwargs.pop("group_qs")
super().__init__(*args, **kwargs)
self.fields["group"].queryset = qs
class Meta:
model = User
fields = [
'username',
'email',
'password1',
'password2',
'group',
'roles',
]
def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Parolalar eşleşmiyor!")
return password2
def clean_email(self):
email = self.cleaned_data.get('email')
lenghtw = len(User.objects.filter(email=email))
if lenghtw > 0 :
raise forms.ValidationError('Bu email adresine sahip bir kullanıcı zaten var.')
return email
views.py
def calisan(request):
queryset = request.user.groups
form = CalisanForm(request.POST or None, group_qs=queryset)
if form.is_valid():
user = form.save()
group = form.cleaned_data['group']
user.groups.add(AGroup.objects.get(name=group))
username = form.cleaned_data['username']
member = Member.objects.create(first_name=username)
group = Group.objects.get(name=form.cleaned_data['group'])
group.add_member(member)
user.save()
password = form.cleaned_data.get('password1')
new_user = authenticate(username=user.username, password=password)
return redirect('home')
return render(request, 'accounts/calisan/calisan.html', 'form': form, 'title': 'Üye Ol')
答案
group.add_member(member, [form.cleaned_data.get('roles')])
add_member
接受的参数:
member
:成员(必填)roles
:角色列表。每个角色可以是角色ID,角色标签或代号,角色实例(可选,默认值:[]
)expiration_date
:指定成员资格的时间戳到期。请注意,这不会自动删除成员来自组,但仅是外部应用程序的指标检查会员资格是否仍然有效(可选,默认值:None
)
以上是关于Django-如何保存所选角色?的主要内容,如果未能解决你的问题,请参考以下文章