How do I show only my own group on the member add page?

I’m using django-groups-manager.

Screenshot

I’m already creating my group during registration. Then I make a group selection when adding members on the member insertion page. However, the entire group list appears. But I just want to see the group of person’s who add the user. So, it can include the added user in its own group and cannot access other groups. How can I do it?

forms.py

class CalisanForm(forms.ModelForm):
member = forms.CharField(max_length=100, label='Çalışan Adı')
CHOICES = [( group.name, group.name ) for group in Group.objects.filter()]
new_group_name = forms.ChoiceField(choices=CHOICES,widget = forms.widgets.RadioSelect())

class Meta:
    model = User
    fields = [
        
        'member',
        'new_group_name',
    ]

views.py

def calisan(request):
form = CalisanForm(request.POST or None)
if form.is_valid():
    member_name = form.cleaned_data['member']
    member = Member.objects.create(first_name=member_name)
    group = Group.objects.get(name=form.cleaned_data['new_group_name'])
    group.add_member(member)
    return redirect('home')
return render(request, 'accounts/calisan/calisan.html', {'form': form})

you have to thread it through the layers, passing the choices you want from the view to the form, example code below. It uses ModelChoiceField instead of ChoiceField because then you don’t have to create your own choices list.

I also don’t think you should be using ModelForm in this case - because you’re not using it to create a User. So you don’t need the class Meta on the form class either.

form

class CalisanForm(forms.Form):
    name = forms.CharField(max_length=100, label='Çalışan Adı')
    group = forms.ModelChoiceField(
        queryset=Groups.objects.all(),
        widget=forms.widgets.RadioSelect()
    )

    def __init__(self, *args, **kwargs):
        qs = kwargs.pop("group_qs")
        super().__init__(*args, **kwargs)
        self.fields["group"].queryset = qs

view (function):

def calisan(request):
    queryset = Group.objects.filter(...)
    form = CalisanForm(request.POST or None, group_qs=queryset)
    if form.is_valid():
        name = form.cleaned_data['name']
        member = Member.objects.create(first_name=name)
        group = form.cleaned_data['group']
        group.add_member(member)
        return redirect('home')
    else:
        return render(request, 'accounts/calisan/calisan.html', {'form': form})

outline of how you do this using a class-based view:

class ClassView(...):
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["group_qs"] = Group.objects.filter(...)
        return kwargs
1 Like

@takkaria I’m new to Django (…) What should it be?

From the information you’ve given I can’t tell. How do you know what groups the current user is in? Have you defined a link between a member and a user?

@takkaria When I register to my site, I create my group in the user registration form. I automatically join my group directly when I become a member. I’m logging in. Then, I want to add a new user. I want this user to be included in the group I created when I became a member. We need to be in the same group.

Sorry - I understand conceptually what’s going on but without the code I can’t help any further. What code would you write to show the current user’s Member object in a view? Do you have a custom user model or are you using a user profile to associate the member and the user together? Or do you have a custom Member class?

@takkaria There is no special connection between the user and the member. Both have the same status. What codes do you want (views.py codes?)

There is no special connection between the user and the member. Both have the same status.

That’s your problem then - if there is no link between them how do you know which user record relates to which member?

What codes do you want (views.py codes?)

The view for the user registration form would be useful I think.

forms.py

class RegisterForm(UserCreationForm):
username = forms.CharField(max_length=100, label='Kullanıcı Adı')
email = forms.EmailField(max_length=200, help_text='Required')
new_group_name = forms.CharField(max_length=100, label='Grup Adı')
password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput)
password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput)

class Meta:
    model = User
    fields = [
        'username',
        'email',
        'new_group_name',
        'password1',
        'password2',
    ]

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 register_view(request):
form = RegisterForm(request.POST or None)
if form.is_valid():
    user = form.save()
    new_group_name = form.cleaned_data['new_group_name']
    new_group, created = Group.objects.update_or_create(name=new_group_name)
    user.groups.add(AGroup.objects.get(name=new_group_name))
    user.save()
    password = form.cleaned_data.get('password1')
    new_user = authenticate(username=user.username, password=password)
    login(request, new_user)
    return redirect('home')
return render(request, 'accounts/form.html', {'form': form, 'title': 'Üye Ol'})

Ah OK, so it looks like members and users are kept in sync - do you have AUTH_MODELS_SYNC turned on?

It looks like queryset = request.user.groups might get you what you want

1 Like

@takkaria Thank you so much. Thanks to you, the problem is solved.

You’re welcome! :sparkles:

May I ask one more thing? Can I also set the member’s password? How do I add a password section?

Django’s documentation has you covered here :slight_smile: take a look at the authentication system docs, in particular changing passwords.

I don’t want to change the password. I want to add password. :pleading_face: Can you show it in code?

I pointed you to that page because it shows a user object has set_password() function. Try it out :slight_smile:

I did that. It gives an error.

AttributeError at /accounts/calisan/calisan

‘Member’ object has no attribute ‘set_password’

views.py

def calisan(request):
    queryset = request.user.groups
    form = CalisanForm(request.POST or None, group_qs=queryset)
    if form.is_valid():
        name = form.cleaned_data['name']
        member = Member.objects.create(first_name=name)
        group = Group.objects.get(name=form.cleaned_data['group'])
        group.add_member(member)
        password = form.cleaned_data.get('password1')
        member.set_password(password)
        return redirect('home')
    else:
        return render(request, 'accounts/calisan/calisan.html', {'form': form})

forms.py

class CalisanForm(forms.Form):
name = forms.CharField(max_length=100, label='Çalışan Adı')
group = forms.ModelChoiceField(queryset=Group.objects.all(), widget=forms.widgets.RadioSelect(), empty_label=None)
password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput)
password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
    qs = kwargs.pop("group_qs")
    super().__init__(*args, **kwargs)
    self.fields["group"].queryset = qs

class Meta:
    model = User
    fields = [
        
        'name',
        'group',
        'password1',
        'password2',
    ]
    
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

At the moment it looks like you’re creating a Member, and then the groups manager package is creating a user for you in through its synchronisation functionality. But Members don’t have a set_password method - Users do. So you’d have to create a User here to be able to set its password.

(just a note - I moved this topic to Using Django as it’s not about working on Django code itself)

1 Like