2015-08-28 52 views
2

在模型的形式,我可以覆蓋表單域,像這樣如何重寫窗體域CreateView的

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

如何使用基於視圖CreateView類相同的功能,這樣我就可以覆蓋表單字段?

我試過get_form_kwargsget_form但都是徒勞的。我是否需要創建模型表單?

+1

[如何使用CreateView的用的ModelForm(http://stackoverflow.com/questions/5773724/how-do-i-use-createview-with-a-modelform) –

回答

3

要在您的視圖中使用您的模型表單,請設置form_class。在你的情況下,你也需要重寫get_form_kwargs,這樣你就可以將user傳遞給表單。

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 
4

可以覆蓋get_form_kwargs並通過userkwargs字典。然後在您的__init__()方法中,在表單上設置您的字段。

views.py

通過重寫get_form_kwargs()傳入kwargsuser

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

現在,重寫__init__()方法。在這種情況下,請從kwargs中彈出user密鑰並使用該值創建您的字段。

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