I’m trying to access an authenticated 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:
Imho this is a much cleaner approach as messing with local threads.