我想覆盖表格管理员中的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
答案 0 :(得分:2)
admin.TabularAdmin
没有get_form
方法。
您定义的get_form
函数永远不会被调用。
您可能需要查看get_formset
方法。
答案 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