I have many objects in categories. like
English
etc
French
I tried to display that categories into multiplechocieField
. So I'm using following code. But its just display last object like. French
Here is my forms.py
class UserProfileForm(forms.Form):
categories = Category.objects.all()
for c in categories:
CHOICES = ((c.id,c.name),)
answers = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=CHOICES)
Will you please help me? thank you
UPDATE : I tried Chewie solution. But Now i'm getting TemplateSyntaxError at /users/profile/ Caught ValueError while rendering: need more than 1 value to unpack
You are reassigning (not appending) a new value to CHOICES
in every iteration of the for
loop. It should be something like:
class UserProfileForm(forms.Form):
categories = Category.objects.all()
CHOICES = []
for c in categories:
CHOICES.append((c.id, c.name))
answers = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=CHOICES)
And anyway, perhaps you should be using a proper ForeignKey
for that field.
But if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever.
https://docs.djangoproject.com/en/1.3/ref/models/fields/#choices
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.