问题描述
我想用当前用户过滤ModelChoiceField。我找到了一个非常想解决的解决方案,但我不理解
I want for filter a ModelChoiceField with the current user. I found a solution very close that I want to do, but I dont understandDjango: How to get current user in admin forms
接受的回答为
我现在可以通过访问self.current_user来访问form.ModelForm中的当前用户。
"I can now access the current user in my forms.ModelForm by accessing self.current_user"
-admin.py
class Customer(BaseAdmin):
form = CustomerForm
def get_form(self, request,obj=None,**kwargs):
form = super(Customer, self).get_form(request, **kwargs)
form.current_user = request.user
return form
-forms.py
class CustomerForm(forms.ModelForm):
default_tax = forms.ModelChoiceField(queryset=fa_tax_rates.objects.filter(tenant=????))
class Meta:
model = fa_customers
如何在m上获取当前用户odelchoice queryset(tenant = ????)
如何在modelform(forms.py)中调用self.current_user
How do I get the current user on modelchoice queryset(tenant=????)How do I call the self.current_user in the modelform(forms.py)
推荐答案
覆盖 CustomerForm
的 __ init __
构造函数:
class CustomerForm(forms.ModelForm):
...
def __init__(self, *args, **kwargs):
super(CustomerForm, self).__init__(*args, **kwargs)
self.fields['default_tax'].queryset =
fa_tax_rates.objects.filter(tenant=self.current_user))
表单字段定义中的查询集可以安全地设置为 all()
或 none()
:
Queryset in the form field definition can be safely set to all()
or none()
:
class CustomerForm(forms.ModelForm):
default_tax = forms.ModelChoiceField(queryset=fa_tax_rates.objects.none())
这篇关于Django:ModelForm管理员的当前用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!