Access to authenticated user outside view

I am trying to access an authenticated user in a form class. I played with passing the request object from the view to the init class, but it seemed messy. Is there a better way to access an authenticated user or request an object outside of the view?

class LicenseForm(forms.Form):
    '''def __init__(self, *args, **kwargs):
    #self.fields['license'] = forms.ModelChoiceField(queryset=self.license_queryset(), empty_label='None', widget=forms.RadioSelect())'''

    def license_queryset():
        queryset = License.objects.filter(organization__isnull=True)
        # add addtional filters if the logged in user belongs to an organization
        return queryset

    licenses = forms.ModelChoiceField(queryset=license_queryset(), empty_label='None', widget=forms.RadioSelect())
+3
source share
1 answer

Yes, you can do it, here are the instructions: http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser

Although this works, I personally would prefer to pass the user to the form in the view. This is less like a hack.

, , . ?

Update: - :

class LicenseForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(LicenseForm, self).__init__(*args, **kwargs)
        self._user = kwargs.get('user',None)
        self.fields['licenses'] = forms.ModelChoiceField(queryset=self.license_queryset(), empty_label='None', widget=forms.RadioSelect())

    def license_queryset(self):
        queryset = License.objects.filter(organization__isnull=True)
        if self._user and self._user.belongsTo('SomeOrganization'):
            queryset  = queryset.filter(whatever='fits')
        return queryset

Imho - , .

+2

Source: https://habr.com/ru/post/1731484/


All Articles