Py学习  »  Django

[精华] 请教,在Django模版中使用什么才能够迭代出列表中的索引值?

woz24416 • 10 年前 • 7961 次点击  

在学习Django book中,看到书数据酷这一章节中的案例,views不能没有问题,但书中没有提供template部分的代码自己尝试着补全的时候,发现如果希望页面出现:第N个问题是:xxx。这个效果的时候,xxx部分没有问题,但是N这个数值怎样也出不来,想请教一下怎样在模版中迭代出这个数值。尝试了一下enumerate,发现模版中不支持。具体代码如下:

# views.polls_list:

def polls_list(request):
    db = MySQLdb.connect(user='gaaa', db='polls', passwd='xxx', 
                               host='localhost') 
    cursor = db.cursor()  
    cursor.execute('SELECT question FROM polls_poll ORDER BY 
                         pub_date') 
    questions = [row[0] for row in cursor.fetchall()] 
    db.close()  
    return render_to_response('poll_list.html',locals())

# templates.poll_list.html
{% extends "base.html" %}

{% block title %}polls list{% endblock %}

{% block content %}
<ul>
    {% for question in questions %}
            <li>{{question}}</li>  #这个循环可以正常显示
    {% endfor %}
</ul>
{% endblock %}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/771
 
7961 次点击  
文章 [ 3 ]  |  最新文章 10 年前
woz24416
Reply   •   1 楼
woz24416    10 年前

@Django中国社区 @ duoduo3369非常感谢。您们的帮助已经解决了这个问题。看来还是自己学习的不扎实,再次感谢!!!

duoduo3369
Reply   •   2 楼
duoduo3369    10 年前

django template语法还是比较弱的, 用mako,django-mako可以在模板里面使用任何的python代码

Py站长
Reply   •   3 楼
Py站长    10 年前

Django provides it you can use {{forloop.counter}} index start at 1 or {{forloop.counter0}} index start at 0.

More info at Django template forloop

https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#for