如何根据request.user覆盖django管理表单的外键

时间:2012-08-31 08:14:02

标签: python django django-1.3


admin.py

class PromoAdmin(admin.modelAdmin)
      list_display = ( 'name', 'id', 'category', 'promo_type', 'store', 'brand', 'date_start' )
      form = SampleForm

forms.py

class SampleForm(forms.ModelForm):
class Meta:
     model = Promo

def __init__(self, request *args, **kwargs):
    super(PromoAdminForm, self).__init__(*args, **kwargs)
    self.fields["store"].queryset = Store.objects.filter(onwer=request.user)

请求时出错

Django版本:1.3.1 异常类型:TypeError 例外价值:
init ()至少需要2个参数(给定1个)

1 个答案:

答案 0 :(得分:0)

您无法在字段声明中使用request.user启动store字段。您可以尝试以下方法:

class MyAwesomeForm(forms.ModelForm):
    store = forms.ModelChoiceField(Store.objects)
    class Meta:
       model = Promo

def __init__(self, user, *args, **kwargs):
    super(MyAwesomeForm, self).__init__(*args, **kwargs)
    self.fields['store'].queryset = Store.objects.filter(owner=user)

在实例化表单时,您可以传递request.user对象。

myform = MyAwesomeForm(request.user)

如果您想在管理员中实现这一目标,可以尝试this 为了在管理员中仅提供与登录用户相关的对象,可以覆盖ModelAdmin.queryset函数:

class MyModelAdmin(admin.ModelAdmin):
    form = MyAwesomeAdminForm()
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(store__owner=request.user)

class MyAwesomeAdminForm(forms.ModelForm):
    class Meta:
       model = Promo

请注意,store__owner仅在您的促销模型中存储了外键字段时才有效:

class Promo(models.Model):
    store = models.ForeignKey(Store)

class Store(models.Model):
    owner = models.ForeignKey(User)

我认为也应该可以以某种方式将请求传递给表单的init方法。但没有找到合适的方法来做到这一点。