0

help please fill in the drop down list dynamically form values ​​from the database.

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 }}

resulting error is displayed:

'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
1
  • this is solve problem. thnanks! Commented May 18, 2014 at 9:57

1 Answer 1

2

In ChoiceField, choices works like this:

CHOICES=(
    ('id1', _("value1")),
    ('id2', _("value2")),
)

So, to get choices in your choice field gender, you have to build a list like above.

Here is how I do:

CHOICES=[]
for x in Gender.get_gender_list():
   CHOICES.append((x.id, x.gender))

Finally:

class SearchFriendsForm(forms.Form):
    gender = forms.ChoiceField(
        widget=forms.Select, 
        choices=CHOICES,
        label='Пол',
    )
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.