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 –

相关问题