在Django Admin Form中按用户过滤ModelChoiceField

时间:2014-09-22 10:40:14

标签: python django django-forms django-admin

我是Django的新手,我创建了一个具有这种结构的项目:

model.py

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

class MyModel(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(User, null=True, blank=True)
    group = models.ForeignKey(Group, null=True, blank=True)
    ...
    ...

admin.py

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
    ...

    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        # If super-user, show all records
        if request.user.is_superuser:
            return qs
        # If user have group, show all records of the group
        if request.user.groups.all().count() > 0:
            return qs.filter(group=(request.user.groups.all()))
        #Show only the records that the user have been created
        return qs.filter(created_by=request.user)

我想只显示分配给特定组的记录。没关系,但是如何创建我在admin.py中使用的相同过滤器来过滤我的Django表单中用户组的选择?我怎样才能传递登录到ModelForm类的实际用户?

Forms.py

class MyModelForm(forms.ModelForm):
    group = forms.ModelChoiceField(Group.objects.filter(id=####),
                label=ugettext_lazy("Groups"), required=True)

谢谢!

2 个答案:

答案 0 :(得分:2)

您不能在字段定义中执行此操作,因为您需要请求对象。我认为唯一的方法是在管理类上定义formfield_for_dbfield

def formfield_for_dbfield(self, db_field, request, **kwargs):
    field = super(MyModelAdmin, self).formfield_for_dbfield(db_field, request, **kwargs)
    if db_field.name == 'groups':
        field.queryset = field.queryset.filter(user=request.user)
    return field

没有测试过代码,所以可能是错的: - )

答案 1 :(得分:2)

formfield_for_dbfield我已经找到了答案:)

admin.py

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
    ...
    def get_form(self, request, obj=None, **kwargs):
        kwargs['formfield_callback'] = partial(self.formfield_for_dbfield, request=request)
        return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

    def formfield_for_dbfield(self, db_field, **kwargs):
        field = super(MyModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'group':
            field.queryset = field.queryset.filter(id__in=(kwargs['request'].user.groups.all()))
        return field