开发者

Access authenticated user outside of a view

I'm trying to access an authen开发者_如何学Cticated user within a form class. I played with passing the request object from a viewto the class init, but it seemed sloppy. Is there a better way to access the authenticated user or request object outside of a 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())


Yes you can do it, here are 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 feels less like a hack.

You could also show your code, maybe it can be improved. Why do you have to access the user in the form?

Update: You could do something like this:

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 this is a much cleaner approach as messing with local threads.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜