将用户名传递给Django表单

时间:2018-05-08 20:01:24

标签: python django forms kwargs

所以我有一个自定义表单,我需要传递request.user.username,以便我可以根据用户访问它来填写forms.ModelChoiceField。 这就是我所拥有的

views.py

if request.method == 'POST':
    form = DepartmentForm(request.POST, username=request.user.username)
    # Do stuff
else:
     form = DepartmentForm(username=request.user.username)

forms.py

class DepartmentForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.username = kwargs.pop('username', None)
        super(DepartmentForm, self).__init__(*args, **kwargs)

    Company = forms.ModelChoiceField(queryset=Company.objects.raw('''
      SELECT DISTINCT c.id, c.name, c.createdBy, c.allowedTeam_ID FROM projects_company AS c
      LEFT JOIN auth_user_groups AS aug ON c.allowedTeam_id=aug.group_id
      LEFT JOIN auth_user AS au ON aug.user_id=au.id
      WHERE au.username = %s OR c.createdBy = %s''',
     [self.username, self.username]),
     empty_label='Select company', widget=forms.Select(attrs={'class': 'materialSelect', 'id': 'companyDropdown'}))

但是当我尝试选择填写self.username时,我得到一个NameError:名称'self'未定义

我试着寻找我的解决方案,但我找到的那个似乎没有用。 我很感激你们给予的任何帮助。 如果您需要更多信息,请不要犹豫,我会相应更新问题。 这是我得到的错误

第25行,在DepartmentForm中     [self.username,self.username]), NameError:未定义名称“self” 我是基于self.username

选择的查询的结尾

2 个答案:

答案 0 :(得分:3)

加载模块时会评估行Company = forms.ModelChoiceField()。此时您无法访问self.username

相反,您应该在表单queryset方法中设置__init__

class DepartmentForm(forms.Form):
    company = forms.ModelChoiceField(
        queryset=Company.objects.none(),  # use empty queryset now, we'll set the real queryset when the form is initialised
        widget=forms.Select(...),
    )

    def __init__(self, *args, **kwargs):
        self.username = kwargs.pop('username', None)
        super(DepartmentForm, self).__init__(*args, **kwargs)

        self.fields['company'].queryset = Company.objects.raw(...)

答案 1 :(得分:0)

您可以使用字典预填任何字段:

if request.method == 'POST':
    # do stuff
else:
    form = DepartmentForm({"username":request.user.username})

if request.method == 'POST':
    # do stuff
else:
    form = DepartmentForm()
    form.initial = {"username":request.user.username}