Django表单和django-guardian:显示UserObjectPermissions的过滤列表

时间:2014-08-21 14:34:53

标签: python django permissions django-guardian

我希望管理员能够根据所述对象可用的权限,为一个人分配/删除django-guardian权限以及它们与Project对象的关系。

屏幕看起来像这样:

User dropdown followed by checklist of permissions

项目在URL中提供,视图可以看到。我创建了一个自定义表单,它将项目作为输入,如下所示:

from django import forms
from django.contrib.auth.models import User
from guardian.shortcuts import get_perms_for_model

class ProjectAssignmentForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.p = kwargs.pop('project')
        self.perms = [(x, x) for x in get_perms_for_model(self.p)]
        super(ProjectAssignmentForm, self).__init__(*args, **kwargs)
        self.fields['permission'].widget = forms.CheckboxSelectMultiple()

    user = forms.ModelChoiceField(queryset=User.objects.all())  
    permission = forms.ChoiceField(choices=self.perms)

这当前给了我一个NameError,我想因为我在self方法之外使用__init__。我做错了什么?

1 个答案:

答案 0 :(得分:0)

嗯,这很令人尴尬。这就是答案 - 我几乎拥有它:

from django import forms
from django.contrib.auth.models import User
from guardian.shortcuts import get_perms_for_model

class ProjectAssignmentForm(forms.Form):
  def __init__(self, *args, **kwargs):
    super(ProjectAssignmentForm, self).__init__(*args, **kwargs)
    self.fields['permission'].widget = forms.CheckboxSelectMultiple(
        choices=[(x, x) for x in get_perms_for_model(kwargs.pop('project'))])

  user = forms.ModelChoiceField(queryset=User.objects.all())  
  permission = forms.MultipleChoiceField()