在 Django 模板中获取模型 ID

Pac*_*cha 1 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))
Run Code Online (Sandbox Code Playgroud)

我想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>
Run Code Online (Sandbox Code Playgroud)

但是movie_id是空的。

Aam*_*nan 5

这一行<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>
Run Code Online (Sandbox Code Playgroud)

的范围movie_id就在with块内。

  • 它有效,但完全没有意义,因为不需要在模板中显式转换为字符串。`{{ movie.id }}` 可以正常工作。 (2认同)