【发布时间】:2018-05-01 23:17:57
【问题描述】:
根据 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
【问题讨论】:
标签: django django-models django-forms django-templates django-views