首页 > 解决方案 > 无法在模板中显示模型中的数据

问题描述

我正在尝试显示我内部模型中的数据,该模型post.html以前有效,但现在由于某种原因我无法弄清楚。

网址.py

urlpatterns = [
    path('', ListView.as_view(
        queryset=Tutorials.objects.all().order_by("-date")[:25],
        template_name="tutorials/blog.html"
    )),

    path('<int:pk>', DetailView.as_view(
            model=Tutorials,
            template_name="tutorials/post.html")),
]

博客.html

{% block  python %}
    {% for Tutorials in object_list %}
        {% if Tutorials.categories == "pythonbasics" %}
            <a href="/tutorials/{{ Tutorials.id }}"><h1>{{ Tutorials.title }}</h1></a>
            <br>
            Created On : {{ Tutorials.date|date:"Y-m-d" }}
        {% endif %}
    {% endfor %}
{% endblock %}

post.html

{% block content %}
    <h3>{{ Tutorials.title }}</h3>

    <h6> on {{ Tutorials.datetime }}</h6>

    <div class = "code">
        {{ Tutorials.content|linebreaks }}
    </div>
{% endblock %}

标签: pythondjango

解决方案


您应该object在模板中使用名称:

{% block content %}
    <h3>{{ object.title }}</h3>

    <h6> on {{ object.datetime }}</h6>

    <div class = "code">
        {{ object.content|linebreaks }}
    </div>
{% endblock %}

或者如果你想使用Tutorial变量,你需要传递context_object_name=Tutorials给视图:

path('<int:pk>', DetailView.as_view(
            model=Tutorials,
            template_name="tutorials/post.html",
            context_object_name='Tutorials')),

推荐阅读