I’m using django-groups-manager.
I want to select the role when adding members. I’m listing roles, but I don’t know how to save them. How can I do it?
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'})