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?
django django-forms django-class-based-views
Brian Apr 27 '11 at 3:01 a.m. 2011-04-27 15:01
source share