Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

django - How to override form field in CreateView

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...