Sending request.user object to ModelForm from the general view of the class in Django

So my goal is to be able to filter the ModelChoiceField query set in my ModelForm to include only the places that request.user created.

My ModelForm is simple:

class PlaceEventForm(models.ModelForm): class Meta: model = Event 

I would like to add something like:

 def __init__(self, *args, **kwargs): super(PlaceEventForm, self).__init__(*args, **kwargs) self.fields['place'].queryset = Place.objects.filter(created_by=request.user) 

However, I cannot find a way to access the request in ModelForm.

My view looks like this:

 class PlaceEventFormView(CreateView): form_class = PlaceEventForm template_name = 'events/event_create.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(PlaceEventFormView, self).dispatch(*args, **kwargs) 

I'm not sure if this is even close to what I should do, but I tried:

 def get_form_kwargs(self): kwargs = super(PlaceEventFormView, self).get_form_kwargs() kwargs.update({'place_user': self.request.user}) return kwargs 

But I got an error: init () received an unexpected keyword argument 'place_user'

Any ideas on this? Or can anyone think of a way to filter my ModelChoiceField in a view without having to pass my request to ModelForm?

+12
django django-forms django-class-based-views
Apr 27 '11 at 3:01 a.m.
source share
2 answers

You need to put the user key from kwargs into the PlaceEventForm.__init__() method so that it does not go to the ModelForm.__init__() method:

views.py:

 class PlaceEventFormView(CreateView): form_class = PlaceEventForm template_name = 'events/event_create.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(PlaceEventFormView, self).dispatch(*args, **kwargs) def get_form_kwargs(self): kwargs = super(PlaceEventFormView, self).get_form_kwargs() kwargs.update({'place_user': self.request.user}) return kwargs 

forms.py:

 class PlaceEventForm(models.ModelForm): class Meta: model = Event def __init__(self, *args, **kwargs): user = kwargs.pop('place_user') # now kwargs doesn't contain 'place_user', so we can safely pass it to the base class method super(PlaceEventForm, self).__init__(*args, **kwargs) self.fields['place'].queryset = Place.objects.filter(created_by=user) 
+20
Apr 27 '11 at 16:31
source share

I am on an iPhone, but I will do the following:

 def get_form(self, form_class): form = super(MyView, self).get_form(form_class) form.fields['place'].querset = Place.... return form 

Wow, that was hard! No support for retreats!

+1
Apr 27 '11 at 17:26
source share



All Articles