Django auth:组长

时间:2012-01-04 12:01:11

标签: django django-authentication

我的应用程序有大约100个用户和大约10到20个组。现在,客户希望为团队领导者提供特权。

你会怎样做(以可重复使用的方式)?

2 个答案:

答案 0 :(得分:0)

您可以创建一个扩展group类的新模型,并将新外键添加到user(领导者)

答案 1 :(得分:0)

#------------------------------------------
# models.py of fooapp

from django.db import models
from django.contrib.auth.models import User, Group

class GroupLeader(models.Model):
    user=models.OneToOneField(User, primary_key=True)
    groups=models.ManyToManyField(Group, related_name='leaders')
    class Meta:
        verbose_name_plural=u'Group Leaders'

下一个片段使django admin中的小组负责人可用:

#-----------------------------------------
# admin.py of fooapp
# See http://stackoverflow.com/questions/2216974/django-modelform-for-many-to-many-fields
from django.contrib.auth.admin import GroupAdmin
from fooapp.models import GroupLeader

class MyGroupForm(forms.ModelForm):
    class Meta:
        model=Group
    leaders = forms.ModelMultipleChoiceField(queryset=User.objects.all())

    def __init__(self, *args, **kwargs):
        if 'instance' in kwargs:
            # We get the 'initial' keyword argument or initialize it
            # as a dict if it didn't exist.                
            initial = kwargs.setdefault('initial', {})
            # The widget for a ModelMultipleChoiceField expects
            # a list of primary key for the selected data.
            initial['leaders'] = [t.pk for t in kwargs['instance'].leaders.all()]

        forms.ModelForm.__init__(self, *args, **kwargs)
        self.fields['leaders'].widget.attrs['size']=10

    def save(self, commit=True):
        instance = forms.ModelForm.save(self, False)

        # Prepare a 'save_m2m' method for the form,
        old_save_m2m = self.save_m2m
        def save_m2m():
           old_save_m2m()
           instance.leaders.clear()
           for leader_user in self.cleaned_data['leaders']:
               leader_obj, created = GroupLeader.objects.get_or_create(pk=leader_user.pk) # User object to GroupLeader object
               instance.leaders.add(leader_obj)
        self.save_m2m = save_m2m

        # Do we need to save all changes now?
        if commit:
            instance.save()
            self.save_m2m()


        return instance

class MyGroupAdmin(GroupAdmin):
    form=MyGroupForm
admin.site.unregister(Group)
admin.site.register(Group, MyGroupAdmin)