Python Django 4.2.5教程:渲染HTML模板页面(使用render函数来渲染)

目录结构

在这里插入图片描述

vim django-20231002/mysite/polls/views.py

from django.shortcuts import render
from .models import Question
def latest_question_list(request):
    latest_question_list = Question.objects.order_by('-published_time')[:5]
    context = {
    
    'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

vim django-20231002/mysite/polls/urls.py

from django.urls import path
from . import views

urlpatterns=[
    path('index/',views.index,name='index'),
    path('<int:question_id>/',views.q_detail),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
    path('latest_question_list/',views.latest_question_list,name='latest_question_list'),
]

vim django-20231002/mysite/polls/templates/polls/index.html

{
    
    % 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 %}

links:
一个快捷函数: render()

猜你喜欢

转载自blog.csdn.net/a772304419/article/details/133531436