django:覆盖get_Form内联

时间:2015-03-08 06:21:42

标签: python django django-admin inlines

我想覆盖表格管理员中的get_form,以便按当前用户进行过滤。 问题是我收到了错误:

 object has no attribute 'current_user'
  • Admin.py

    class InvoiceDetail(admin.TabularAdmin):
        form = InvoiceDetailForm
        model = fa_invoice_lines
    
        def get_form(self, request, obj=None, **kwargs):
            form = super(InvoiceDetail, self).get_form(request, obj, **kwargs)
            form.current_user = request.user
            return form
    
    class Invoice(admin.ModelAdmin)
        form = InvoiceForm
        inlines =   [InvoiceDetail,]
    
  • Form.py

    class InvoiceDetailForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(InvoiceDetailForm, self).__init__(*args, **kwargs)
            self.fields['item'].queryset = fa_items.objects.filter(tenant=self.current_user)
    
        class Meta:
            model = fa_invoice_lines
    

我在非内联中使用了相同的策略并且它有效 似乎没有调用get_form

2 个答案:

答案 0 :(得分:2)

admin.TabularAdmin没有get_form方法。 您定义的get_form函数永远不会被调用。

您可能需要查看get_formset方法。

https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_formsets

答案 1 :(得分:2)

受到the docs的启发,我实施了以下解决方案:

class Invoice(admin.ModelAdmin)
    form = InvoiceForm
    inlines =   [InvoiceDetail,]

def get_formsets_with_inlines(self, request, obj=None):
    for inline in self.get_inline_instances(request, obj):
        inline.form.current_user = request.user
        yield inline.get_formset(request, obj), inline