根据Django文档,ChoiceField接受an iterable of two tuples, "or a callable that returns such an iterable"作为该字段的选择。
我已在表单中定义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
答案 0 :(得分:3)
使用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
在您的表单中,从__init__
方法中的kwargs参数中选择并在字段上设置选项:
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
瞧!
答案 1 :(得分:3)
另一种简单的方法是:
class PairRequestView(FormView):
form_class = PairRequestForm
def get_form(self, *args, **kwargs):
requester_obj = Profile.objects.get(user__username=self.request.user)
favorites_set = requester_obj.get_favorites()
form = super().get_form(*args, **kwargs)
form.fields['favorite_choices'].choices = favorites_set
return form
答案 2 :(得分:0)
您应该将选择内容封装在表单构造者的适当参数中。假设您有一个“组”下拉菜单,并且想传递“组选择”:
class CreateAccountForm(forms.Form):
def __init__(self, groupChoices_, *args, **kwargs):
super(CreateAccountForm, self).__init__(*args, **kwargs)
self.fields['group'].choices = groupChoices_
group = forms.ChoiceField()
在您看来,始终将groupChoices_用作第一个参数,例如:
groupChoices = [
(2, 'A'),
(4, 'B'),
]
form = CreateAccountForm(groupChoices, request_.POST)
无需担心kwargs
的可怕性!