如何在forms.py中获取当前签名用户?

时间:2016-10-30 11:39:52

标签: python django django-forms django-authentication

我使用ModelChoiceField在表单中选择Invoice provider。在目前的情况下,我将所有提供者返回到查询集。

但是我应该只返回由签名用户创建的提供者。 Provider有一个名为user的ForeignKey字段。

这是我的表格:

class InvoiceCreationForm(forms.Form):
    # ...
    provider = forms.ModelChoiceField(
        label='Provider',
        required=False,
        queryset=Provider.objects.all(),
        widget=forms.Select(attrs={
            'name': 'provider',
            'class': 'form-control',
            'id': 'input-invoice-provider',
        })
    )

我需要过滤这样的对象:

Provider.objects.filter(user=current_user)

如何获得签名用户?或者如何在视图外部获取request对象?我尝试从表单的__init__方法获取当前用户,然后将其设置为self.user。但我无法在self.user等查询中使用它。

1 个答案:

答案 0 :(得分:1)

让用户进入__init__()只是解决方案的第一部分。您还需要使用该用户来过滤查询集:

class InvoiceCreationForm(forms.Form):
    def __init__(self, *args, **kwargs):
         self.user = kwargs.pop('user', None)
         super(InvoiceCreationForm, self).__init__(*args, **kwargs)
         if self.user:
             self.fields['provider'].queryset = Provider.objects.filter(user=self.user)
相关问题