使用user.get_profile()自定义查询Django ModelChoiceField

时间:2011-06-13 23:30:50

标签: django user-profile django-queryset

我想知道如何在创建时访问用户的个人资料 ModelChoiceField的queryset。我希望能够使用 ModelChoiceField基于a显示来自另一个表的联系人 保存在用户配置文件中的参数,即

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

有没有更好的方法来做到这一点(除了ajax选择器之外) 模板)?

Greg

1 个答案:

答案 0 :(得分:2)

对于那些感兴趣的人,我能够从以下SO讨论中找到解决方案:

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)

我的观点:

保存表单(不必在此处包含request = request,但以防万一)

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

或空表格

form = InspectionRequestForm(request=request)

感谢Daniel Roseman先前的答案。

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

相关问题