【问题标题】:Custom Query for Django ModelChoiceField using user.get_profile()使用 user.get_profile() 对 Django ModelChoiceField 进行自定义查询
【发布时间】:2011-09-14 07:40:15
【问题描述】:

我想知道在创建 ModelChoiceField 的查询集。我希望能够使用 ModelChoiceField 显示来自另一个表的联系人,基于 保存在用户配置文件中的参数,即

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

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

格雷格

【问题讨论】:

    标签: django user-profile django-queryset


    【解决方案1】:

    对于那些感兴趣的人,我能够从以下 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

    【讨论】:

      猜你喜欢
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 2014-05-15
      • 1970-01-01
      • 2011-07-31
      • 2014-11-15
      • 1970-01-01
      • 2020-06-28
      相关资源
      最近更新 更多