0

I've looked everywhere and can't seem to find the answer for this problem I'm having and was wondering if anyone would be kind enough to help.

I am trying to display the choices itself (Q_TYPE) as a list of radio buttons in a template. I've tried "get_FOO_display", but it seems that it only displays something if attached to another value.

Below is my best attempt out of many and what I am looking for. If anyone could help me with the problem I would really appreciate it. Even the keywords I should be looking for I would appreciate. Thanks!

Models.py

Q_TYPE = (
('T', 'Text Question'),
('M', 'Multiple Choice'),
)

class Question(models.Model):
   form = models.ForeignKey(Form)
   textquestion = models.CharField(max_length=200, null=True, blank=True)
   questiontype = models.CharField(('question type'), max_length=1, choices=Q_TYPE)

   def __unicode__(self):
       return self.textquestion

Template

{% for questiontype in q_type %}
    {{ questiontype }} <input type="radio" name="{{ questiontype }}" id="" value="" /><br />
{% endfor %}

What I'm trying to get (< > is a radio button)

 < > Text Question
 < > Multiple Choice
4

1 回答 1

2

您可以将 in 传递Q_TYPE到您的模板上下文中,然后执行以下操作:

视图.py

context = {'Q_TYPE': Q_TYPE}
return render(request, 'mytemplate.html', context)

模板

{% for id, value in Q_TYPE %}
    {{ value }} <input type="radio" name="{{ id }}" id="" value="" /><br />
{% endfor %}

或对循环变量使用索引

{% for item in Q_TYPE %}
    {{ item.1 }} <input type="radio" name="{{ item.0 }}" id="" value="" /><br />
{% endfor %}

但是,正如我在评论中提到的,您应该尝试使用内置ModelForm系统。

于 2012-06-30T22:26:59.257 回答