ModelForm管理员的当前用户ID

ModelForm管理员的当前用户ID

本文介绍了Django:ModelForm管理员的当前用户ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用当前用户过滤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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 17:57