你能自动在模板中显示模型选择吗?

时间:2011-09-06 17:38:50

标签: django django-models django-templates

我是django noob,我有一个django项目,模型设置如下:

class community(models.Model):
    DIRECTION_CHOICES = (
        (u'N', u'North'),
        (u'S', u'South'),
        (u'E', u'East'),
        (u'W', u'West'),
        (u'C', u'City'),
    )
    name = models.CharField(max_length=100)
    direction = models.CharField(max_length = 1, choices=DIRECTION_CHOICES)
    def __unicode__(self):
        return self.name
    class Meta:
        verbose_name = "Community"
        verbose_name_plural = "Communities"

我想添加一个模板页面,它只显示选项链接,如下钻取类型菜单:

 ***Communities***
 * North 
 * South 
 * East 
 * West 
 * City

当您点击其中一个时,您会看到该区域中的社区列表。

我有办法吗

 {% for area in choices %}
     {{ area.name }}
 {% endfor %}

...

1 个答案:

答案 0 :(得分:6)

如何将其添加到表单类并显示选项,如下所示: https://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield

或者,您可以在视图中返回选项,如下所示:

def main(request):
 from app.models.community import DIRECTION_CHOICES

 return render_to_response('my_template.html',
                      {'choices':DIRECTION_CHOICES},
                      context_instance=RequestContext(request))

并在您的模板中:

<select name="direction">
        {% for k,v in choices %}
            <option value="{{ k }}"/>{{ v }}
        {% endfor %}
</select>