How to get request.user to filter data in django forms?

Viewed 980

I have this code:

# forms.py
channels = Channel.objects.filter(company=user)
channel = forms.ChoiceField(
    choices=channels, 
    widget=forms.Select(attrs={'class': 'form-control'})
)

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

def clean_channel(self):
    channel = self.cleaned_data.get('channel')
    if self.user:
        return channel

But user is not deffined.

How to get request.user to filter data in forms?

2 Answers

Another way is to do something like this in your views

channel = forms.ModelChoiceField
    (queryset=Channel.objects.all(), 
    widget=forms.Select(attrs= {'class': 'form-control'}))

So instead of overidding __init__, you do something like this in your In views.py

form = ChannelForm()
form.fields['channel'].queryset = Channel.objects.filter(company=user)
Related