Django: add a user to a group through Django Admin

How to add users to a group in the Django admin interface "Change group"?

I saw dirty hacks for this to work for an older version of django.

How to solve this with Django 1.10?

Emphasize that I want this on the Change Group page, not on the Change User page.

I would like to have this in the style of django-admin: no coding, just doing some configuration. Maybe like this:

class GroupAdmin(admin.ModelAdmin):
    show_reverse_many_to_many = ('user',)
+4
source share
3 answers

You need to write a code. Please note that the Django admin site is the usual Django views and forms!

First create a ModelForm:

from django import forms
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.admin.widgets import FilteredSelectMultiple    
from django.contrib.auth.models import Group


User = get_user_model()


# Create ModelForm based on the Group model.
class GroupAdminForm(forms.ModelForm):
    class Meta:
        model = Group
        exclude = []

    # Add the users field.
    users = forms.ModelMultipleChoiceField(
         queryset=User.objects.all(), 
         required=False,
         # Use the pretty 'filter_horizontal widget'.
         widget=FilteredSelectMultiple('users', False)
    )

    def __init__(self, *args, **kwargs):
        # Do the normal form initialisation.
        super(GroupAdminForm, self).__init__(*args, **kwargs)
        # If it is an existing group (saved objects have a pk).
        if self.instance.pk:
            # Populate the users field with the current Group users.
            self.fields['users'].initial = self.instance.user_set.all()

    def save_m2m(self):
        # Add the users to the Group.
        self.instance.user_set.set(self.cleaned_data['users'])

    def save(self, *args, **kwargs):
        # Default save
        instance = super(GroupAdminForm, self).save()
        # Save many-to-many data
        self.save_m2m()
        return instance

ModelForm. - , ModelForm:

# Unregister the original Group admin.
admin.site.unregister(Group)

# Create a new Group admin.
class GroupAdmin(admin.ModelAdmin):
    # Use our custom form.
    form = GroupAdminForm
    # Filter permissions horizontal as well.
    filter_horizontal = ['permissions']

# Register the new Group ModelAdmin.
admin.site.register(Group, GroupAdmin)

Screenshot Django custom form and filter_horizontal in Group admin

+12

, django admin , M2M, User, m2m to Group .

, , django , , , .

class GroupForm(forms.Form):
    blah
    users = forms.ModelMultipleChoiceField(
        label=_('Users'), required=False, queryset=User.objects.all(),
        widget=FilteredSelectMultiple(is_stacked=True, verbose_name=_('Users')),help_text=mark_safe("Help text")
    )

class GroupAdmin(BaseAdmin):
    form = GroupForm
    # you can here define fieldsets to render your form more beautifully

    def save_related(self, request, form, formsets, change):
        current_group = form.instance
        # ....
        # Update relations between users and the group here, both are
        # accessible with the form instance

    def get_changeform_initial_data(self, request):
        # If you want to render the form with initial data for the user
        # you may optionally override this method as well.
        initial = super(GroupAdmin, self).get_changeform_initial_data(request)
        initial.update({'users': ...})
        return initial

django-ic , , ! , .

+1

" "

0

Source: https://habr.com/ru/post/1654536/


All Articles