G
G
German Jet2015-08-03 12:52:04
Django
German Jet, 2015-08-03 12:52:04

How to get request.user.id in django.forms?

forms.py

class WorkForm(forms.Form):
  road = forms.ModelChoiceField(
    label='Выберите объект', 
    queryset=Roads.objects.filter(contractor=request.user.id))

those. the logged in user must choose from their objects, but
name 'request' is not defined

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tplus, 2015-08-03
@GeraJet

Define your own __init__, where to give the desired parameter.

class WorkForm(forms.Form)

    road = forms.ModelChoicField(label='', queryset=Road.objects.none())

    def __init__(self, *args, **kwargs):
        user_id = kwargs.pop('user_id', None)

        super(WorkForm, self).__init__(*args, **kwargs)

        self.fields['road'].queryset = Roads.objects.filter(contractor=user_id)

Z
zelsky, 2015-08-03
@zelsky

Roads.objects.filter(contractor=request.user.id))
Aren't you trying to extract the user ID from the database?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question