2014-05-18 242 views
0

請從數據庫中動態填寫下拉列表中的值。如何填充下拉列表表單?

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

這是解決問題。 thnanks! – user3607370

回答

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='Пол', 
    )