Django:通过Django Admin将用户添加到组

时间:2016-09-14 07:45:08

标签: django django-admin

如何在Django管理界面中添加用户到#34;更改组"?

我已经看到了肮脏的黑客,以使这适用于较旧的django版本。

如何用Django 1.10解决这个问题?

强调:我希望在页面"更改组"而不是"更改用户"。

我想在django-admin-style中有这个:没有编码,只是做一些配置。也许是这样的:

class GroupAdmin(admin.ModelAdmin):
    show_reverse_many_to_many = ('user',)

3 个答案:

答案 0 :(得分:14)

您需要编写一些代码。请注意,Django管理站点是正常的Django视图和表单!

首先创建一个ModelForm:

otool -TV <object>
nm -a <object>

我们添加了一个自定义的Group ModelForm。第二步是取消注册原始组管理员并注册一个显示我们的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

Screenshot Django custom form and filter_horizontal in Group admin

答案 1 :(得分:1)

你必须编写代码来实现你想要的,因为django admin为其中包含M2M字段的模型提供了更改表单,即User,因为m2m到Group是在里面那个模特。

所以基本上,在django admin中完成它并且很好,你可能需要覆盖几个函数并提供你自己的实现。

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方式!希望它有所帮助或给你一个想法

答案 2 :(得分:0)

在更改群组页面上,您必须覆盖更改群组表单并添加一个包含用户的多个选择框