Is it possible to set Django Admin
page to show which user is in which group? And is it possible to be able to add a user into a group using the Django Admin
page? If yes, how?
Now, I'm adding programmatically customers into customers group
and sellers into sellers group
, but I can't see any information in my administration.
This is my registration view
:
def register_customer(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
customer_registration_form = forms.CustomerRegistrationForm(request.POST)
if form.is_valid() and customer_registration_form.is_valid():
new_user = form.save()
new_customer_profile = UserCustomerProfile(user=new_user)
new_customer_profile.save()
customers_group = Group.objects.get(name='Customers')
new_user.groups.add(customers_group)
return render(request, 'registration/complete.html')
else:
#handle errors
customer_registration_form = forms.CustomerRegistrationForm()
form = UserCreationForm()
return render(request, "registration/register.html",
{'form': form, 'customer_registration_form': customer_registration_form})
CVi's answer worked with some minor tweaks, but for my use case I really wanted another multi-select widget to manage the users in the group just like the multi-select for managing the group's permissions.
Using this answer for inspiration, I came up with this:
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import GroupAdmin as origGroupAdmin
from django.contrib.auth.models import Group, User
class GroupAdminForm(forms.ModelForm):
"""
ModelForm that adds an additional multiple select field for managing
the users in the group.
"""
users = forms.ModelMultipleChoiceField(
User.objects.all(),
widget=admin.widgets.FilteredSelectMultiple('Users', False),
required=False,
)
def __init__(self, *args, **kwargs):
super(GroupAdminForm, self).__init__(*args, **kwargs)
if self.instance.pk:
initial_users = self.instance.user_set.values_list('pk', flat=True)
self.initial['users'] = initial_users
def save(self, *args, **kwargs):
kwargs['commit'] = True
return super(GroupAdminForm, self).save(*args, **kwargs)
def save_m2m(self):
self.instance.user_set.clear()
self.instance.user_set.add(*self.cleaned_data['users'])
class GroupAdmin(origGroupAdmin):
"""
Customized GroupAdmin class that uses the customized form to allow
management of users within a group.
"""
form = GroupAdminForm
# Register the modified GroupAdmin with the admin site
admin_site = admin.AdminSite(name='my_admin')
admin_site.register(Group, GroupAdmin)