1

根據Django文檔,ChoiceField接受an iterable of two tuples, "or a callable that returns such an iterable"作爲該字段的選項。從視圖中,我如何將自定義「選項」傳遞給表單的ChoiceField?

我我的表格中定義ChoiceFields

class PairRequestForm(forms.Form): 
    favorite_choices = forms.ChoiceField(choices=[], widget=RadioSelect, required=False) 

這裏就是我試圖通過自定義選擇元組的觀點:

class PairRequestView(FormView): 
    form_class = PairRequestForm 

    def get_initial(self): 
     requester_obj = Profile.objects.get(user__username=self.request.user) 
     accepter_obj = Profile.objects.get(user__username=self.kwargs.get("username")) 

     # `get_favorites()` is the object's method which returns a tuple. 
     favorites_set = requester_obj.get_favorites() 

     initial = super(PairRequestView, self).get_initial() 

     initial['favorite_choices'] = favorites_set 

     return initial 

在我的models.py,這裏是上面使用的返回元組的方法:

def get_favorites(self): 
     return (('a', self.fave1), ('b', self.fave2), ('c', self.fave3)) 

根據我的理解,如果我想預先填寫表單,我會通過覆蓋get_initial()來傳遞數據。我試圖設置可調用的表單的favorite_choices的初始數據。可調用的是favorites_set

在當前的代碼,我給出的'tuple' object is not callable

錯誤我怎麼能預先填充與我自己的選擇RadioSelect ChoiceField?

編輯:我也試着設置initial['favorite_choices'].choices = favorites_set

回答

1

get_initial方法制成填充表單的域的初始值。不要設置可用的choices或修改您的字段屬性。

要成功地通過你的選擇從您的視圖的形式,你需要實現get_form_kwargs方法在您的視圖:

class PairRequestView(FormView): 
    form_class = PairRequestForm 

    def get_form_kwargs(self): 
     """Passing the `choices` from your view to the form __init__ method""" 

     kwargs = super().get_form_kwargs() 

     # Here you can pass additional kwargs arguments to the form. 
     kwargs['favorite_choices'] = [('choice_value', 'choice_label')] 

     return kwargs 

而在你的形式,得到了kwargs參數的選擇在__init__方法並設置在該領域的選擇:

class PairRequestForm(forms.Form): 

    favorite_choices = forms.ChoiceField(choices=[], widget=RadioSelect, required=False) 

    def __init__(self, *args, **kwargs): 
     """Populating the choices of the favorite_choices field using the favorites_choices kwargs""" 

     favorites_choices = kwargs.pop('favorite_choices') 

     super().__init__(*args, **kwargs) 

     self.fields['favorite_choices'].choices = favorites_choices 

而瞧!

+0

在編輯'self.fields []。choices'之前,您有沒有特別的原因讓您調用'super().__ init __()'調用? – Homer

+1

如果您在之前不調用基礎'__init__',則不會定義任何'fields'屬性。 ''field'屬性在這裏的'BaseForm' init方法中定義:https://github.com/django/django/blob/master/django/forms/forms.py#L95 –

相關問題