10

In model form I can override form field like so

class waypointForm(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ModelChoiceField(queryset=Waypoint.objects.filter(user=user))

How can I use the same functionality in class based view CreateView, so that I can override form field?

I tried get_form_kwargs and get_form but all in vain. Do I need to create a model form?

Alasdair
  • 298,606
  • 55
  • 578
  • 516
Rizwan Mumtaz
  • 3,875
  • 2
  • 30
  • 31
  • 2
    [How do I use CreateView with a ModelForm](http://stackoverflow.com/questions/5773724/how-do-i-use-createview-with-a-modelform) – César Aug 28 '15 at 14:19

2 Answers2

15

You can override the get_form_kwargs and pass the user to kwargs dictionary. Then in your __init__() method, set your field on the form.

views.py

Pass the user in kwargs by overriding the get_form_kwargs().

class MyCreateView(CreateView):

    form_class = waypointForm

    def get_form_kwargs(self):
        kwargs = super(MyCreateView, self).get_form_kwargs()
        kwargs['user'] = self.request.user # pass the 'user' in kwargs
        return kwargs 

forms.py

Now, override the __init__() method. In that, pop the user key from kwargs and use that value to create your field.

class waypointForm(forms.ModelForm):

    def __init__(self, *args, **kwargs): 
        user = kwargs.pop('user', None) # pop the 'user' from kwargs dictionary      
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ModelChoiceField(queryset=Waypoint.objects.filter(user=user)) 
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
5

To use your model form in your view, set form_class. In your case, you need to override get_form_kwargs as well, so that you can pass user to the form.

def CreateWaypointView(CreateView):
    ...
    form_class = WaypointForm

    def get_form_kwargs(self):
        kwargs = super(CreateWaypointView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs
César
  • 9,939
  • 6
  • 53
  • 74
Alasdair
  • 298,606
  • 55
  • 578
  • 516