JKirchartz
JKirchartz

Reputation: 18022

Can you automatically display model choices in a template?

I'm a django noob, I've got a django project with a model setup like:

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"

I'd like to add a template page that just displays links to choices as a drill-down type menu like:

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

and when you click on one you see a list of communities in that area.

Is there a way I can do

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

??

Upvotes: 2

Views: 1764

Answers (1)

Arthur Neves
Arthur Neves

Reputation: 12128

How about you add this into a form class and display the choices, like this: https://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield

Or, you can return the choices in your view, like this:

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

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

and in your template:

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

Upvotes: 6

Related Questions