How to access user.id in forms.py?

I want to be able to access the id of the signed in user in my forms to make a certain query for the Select2 field.

Unfortunately I don’t know how to get the user.id in the forms.py

This is what I’m trying currently in my forms.py:

class InsertVisitRepresentativeForm(ModelForm):
    class Meta:
        model = VisitsRepresentatives
        fields = '__all__'

        widgets = { 
            'customer' : s2forms.ModelSelect2Widget(
                model=VisitsRepresentatives,
                attrs={'data-placeholder':_("Customer"), 'data-minimum-input-length': 1},
                search_fields = ['contactPerson__icontains']
            ),
        }

    def __init__(self, *args, **kwargs):
        super(InsertVisitRepresentativeForm, self).__init__(*args, **kwargs)

        print(self.user)

        postalRepresentativeObject = PostalRepresentative.objects.get(representative = self.user)

        postalCodes = postalRepresentativeObject.postalCodes

        self.fields["customer"].queryset = Customers.objects.filter(Q(postalcode__in = postalCodes) | Q(postalcode__gte =  postalRepresentativeObject.beginPostalRange) & Q(postalcode__lte = postalRepresentativeObject.endPostalRange))

This does not work, so I’m wondering how to get the user id in a ModelForm?

Hi,

I read something about accessing the user and pass it to a form…

here is the link:

Hope it will help.

Yes I do believe this works! Thanks, how did you find this so fast?

you’re welcome… I’m glad that it helped you…

I had a similar issue the other day… I remembered that I read about this…

1 Like