如何在admin中访问django modelform中的request.user

时间:2015-12-04 04:34:32

标签: python django

希望通过覆盖更改列表视图,根据模型管理员中当前登录的用户过滤下拉列表。我正在尝试过滤属于该部门用户的类别的下拉列表

class CategoryForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CategoryForm, self).__init__(*args, **kwargs)

class CategoryAdmin(admin.ModelAdmin):
    list_display = ['department','name']
    list_filter = ['department','name']

    def changelist_view(self, request, extra_context=None):
        extra_context = extra_context or {}
        self.form = CategoryForm
        print dir(self.form)
        self.form.fields['department'].queryset = Department.objects.filter(
            name = request.user.customuser.department.name)

如何实现这一目标?使用django 1.6.5

错误

type object 'CategoryForm' has no attribute 'fields'

1 个答案:

答案 0 :(得分:2)

一般来说,改变ModelForm类的base_fields并不是一种愚蠢的做法,但在这种情况下,每次请求都会生成类,所以它没问题。

android.bluetooth