Django Admin:在ModelForm的构造函数中获取请求

时间:2009-10-15 22:45:48

标签: django admin django-forms init

以下代码会从下拉菜单中删除某些值。 它工作正常,但我想删除该值,如果用户缺少某些权限。 如何在ModelForm的构造函数中访问request.user?或者有更好的方法来完成我想要做的事情吗?

class AnnouncementModelForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(AnnouncementModelForm, self).__init__(*args, **kwargs)
        self.fields["category"].queryset = AnnouncementCategory.objects.filter(can_post=True)   

2 个答案:

答案 0 :(得分:1)

  

如何在ModelForm的构造函数中访问request.user?

要在Form构造函数中使用它,只需将请求传递给它。

class AnnouncementModelForm(forms.ModelForm):

    def __init__(self, request, *args, **kwargs):
        super(AnnouncementModelForm, self).__init__(*args, **kwargs)
        qs = request.user.foreignkeytable__set.all()
        self.fields["category"].queryset = qs

答案 1 :(得分:1)

好的,我是如何解决的:

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "category" and not request.user.has_perm('can_post_to_all'):
        kwargs["queryset"] = AnnouncementCategory.objects.filter(can_post=True)
        return db_field.formfield(**kwargs)
    return super(AnnouncementAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)