NeDiaz
NeDiaz

Reputation: 369

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)

Upvotes: 2

Views: 2261

Answers (2)

VMMF
VMMF

Reputation: 954

Just to sum up the solution because it was very hard for me to make this work and understand the accepted answer

In admin.py

class MyModelForm (forms.ModelForm):

    def __init__(self, *args,**kwargs):
    super (MyModelForm ,self).__init__(*args,**kwargs)
    #retrieve current_user from MyModelAdmin
    self.fields['my_model_field'].queryset = Staff.objects.all().filter(person_name = self.current_user)

#The person name in the database must be the same as in Django User, otherwise use something like person_name__contains

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm 

    def get_form(self, request, *args, **kwargs):
        form = super(MyModelAdmin, self).get_form(request, *args, **kwargs)
        form.current_user = request.user #get current user only accessible in MyModelAdminand pass it to MyModelForm
        return form

Upvotes: 1

catavaran
catavaran

Reputation: 45575

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

Upvotes: 1

Related Questions