在django模板中获取模型ID

时间:2014-06-25 11:48:33

标签: django django-templates django-views

我在views.py

中有这个
def movies_popular(request):
    popular_movies = Movie.objects.all()
    template = loader.get_template('streaming/movies_popular.html')
    context = RequestContext(request, { 'popular_movies': popular_movies })
    return HttpResponse(template.render(context))

我想从模板中访问我的Movie ID,所以我这样做:

    <h2>{{ movie.title }}</h2>
    {% with movie.id|stringformat:"s" as movie_id %}
    {% endwith %}
    <p>Testing ID: "{{ movie_id }}"<p/>
    <p>{{ movie.description }}</p>

但是movie_id是空的。

1 个答案:

答案 0 :(得分:3)

此行<p>Testing ID: "{{ movie_id }}"<p/>应位于with块内:

<h2>{{ movie.title }}</h2>
{% with movie.id|stringformat:"s" as movie_id %}
<p>Testing ID: "{{ movie_id }}"<p/>
{% endwith %}
<p>{{ movie.description }}</p>

movie_id的范围就在with区块内。