Django 在呈现的网站上公开原始 html

Django exposes raw html on a rendered website

我正在通过文档教程学习 Django:

https://docs.djangoproject.com/en/4.0/intro/tutorial03/

我刚刚完成了“编写实际执行某些操作的视图”部分,但肯定有些地方不对劲。即使我复制了代码 1:1,这是我得到的渲染:

我编辑的最后两位代码:

index.html 在 polls/templates/polls 目录中:

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

views.py 在投票目录中:

from django.http import HttpResponse
from django.template import loader

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('polls/index.html')
    context = {
        'latest_question_list': latest_question_list,
    }
    return HttpResponse(template.render(context, request))

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

尝试更新您的视图以使其更简单:

def index(request):
    latest_question_list = Question.objects.all()
    context = {
        'latest_question_list': latest_question_list,
    }
    return render(request, 'polls/index.html', context)