问题描述
||
我想知道在创建帐户时如何访问用户的个人资料
ModelChoiceField的queryset。我希望能够使用
ModelChoiceField以显示基于另一个表的联系人
参数保存在用户个人资料中,即
who = forms.ModelChoiceField(queryset=Contacts.objects.filter(id__exact=request.user.get_profile().main_company))
是否有更好的方法来做到这一点(除了Ajax选择器中的
模板)?
格雷格
解决方法
对于那些感兴趣的人,我能够通过以下SO讨论提出一个解决方案:
如何访问表单的clean()方法中的请求对象或任何其他变量?
Django:从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