帮助请从数据库中动态填写下拉列表中的值。
models.py:
class Gender(models.Model):
gender = models.CharField(
max_length=10,
blank=False,
)
@classmethod
def get_gender_list(self):
return self.objects.all()
forms.py:
class SearchFriendsForm(forms.Form):
gender = forms.ChoiceField(
widget=forms.Select,
choices=Gender.get_gender_list(), # not worked
#choices=(('1', '1'), ('2', '2')), # worked
label='Пол',
)
friends_search.html:
{{ form.gender }}
显示结果错误:
'Gender' object is not iterable
Request Method: GET
Request URL: http://127.0.0.1:8000/userprofile/friends_search/
Django Version: 1.6.2
Exception Type: TypeError
Exception Value:
'Gender' object is not iterable
Exception Location: C:\Python33\lib\site-packages\django\forms\widgets.py in render_options, line 528
答案 0 :(得分:2)
在ChoiceField中,choices
的工作方式如下:
CHOICES=(
('id1', _("value1")),
('id2', _("value2")),
)
因此,要在您选择的字段gender
中进行选择,您必须构建一个类似上面的列表。
我是这样做的:
CHOICES=[]
for x in Gender.get_gender_list():
CHOICES.append((x.id, x.gender))
最后:
class SearchFriendsForm(forms.Form):
gender = forms.ChoiceField(
widget=forms.Select,
choices=CHOICES,
label='Пол',
)