0

I am wondering how to access a user's profile when creating the queryset for a ModelChoiceField. I would like to be able to use the ModelChoiceField to display contacts from another table based on a parameter saved in the user profile i.e.

who = forms.ModelChoiceField(queryset=Contacts.objects.filter(id__exact=request.user.get_profile().main_company))

Is there a better way to do this (beyond an ajax picker in the template)?

Greg

1 Answer 1

2

For Those interested I was able to come up with a solution from the following SO discussions:

How do I access the request object or any other variable in a form's clean() method?

Django: accessing the model instance from within ModelAdmin?

class InspectionRequestForm(ModelForm):
    ....
    def __init__(self, *args, **kwargs):
            self.request = kwargs.pop('request', None)
            super(InspectionRequestForm, self).__init__(*args, **kwargs)
            companyid = self.request.user.get_profile().main_contactnum.clientid.idflcustomernum
            self.fields['who'].queryset = Contacts.objects.filter(clientid__exact=companyid)

My View:

Save Form (Not as necessary to include request=request here, but just in case)

form = InspectionRequestForm(request.POST, request=request)

Or Empty Form

form = InspectionRequestForm(request=request)

Thanks to Daniel Roseman for both of the previous answers.

https://stackoverflow.com/users/104349/daniel-roseman

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.