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

JKi*_*rtz 2 django django-templates django-models

我是一个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"
Run Code Online (Sandbox Code Playgroud)

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

 ***Communities***
 * North 
 * South 
 * East 
 * West 
 * City
Run Code Online (Sandbox Code Playgroud)

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

我有办法吗?

 {% for area in choices %}
     {{ area.name }}
 {% endfor %}
Run Code Online (Sandbox Code Playgroud)

??

Art*_*ves 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))
Run Code Online (Sandbox Code Playgroud)

并在您的模板中:

<select name="direction">
        {% for k,v in choices %}
            <option value="{{ k }}"/>{{ v }}
        {% endfor %}
</select>
Run Code Online (Sandbox Code Playgroud)