开发者

Custom Query for Django ModelChoiceField using user.get_profile()

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 a开发者_StackOverflow中文版nother 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜