Search code examples
djangodjango-admin

Django: Current User Id for ModelForm Admin


I want for filter a ModelChoiceField with the current user. I found a solution very close that I want to do, but I dont understand Django: How to get current user in admin forms?

The answer accepted says

"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

How do I get the current user on modelchoice queryset(tenant=????) How do I call the self.current_user in the modelform(forms.py)


Solution

  • Override __init__ constructor of the CustomerForm:

    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))
    

    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())