Django笔记四 视图和模板

视图

一个视图就是一个页面,提供特定的功能。在Django中,视图其实就是一个简单的python函数(通过函数来处理视图的叫做函数视图,还有一种通过类中的方法来处理视图,这种叫做类视图)

在polls/views.py文件中输入以下代码,会根据发布日期显示最近的5个投票问卷

from django.http import HttpResponse
from .models import Question


# Create your views here.

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    output = ', '.join([q.question_text for q in latest_question_list])
    return HttpResponse(output)

这里页面显示的内容是写死的。如果想要改变内容就只能改python代码。所以这里需要使用模板

模板

模板是用来渲染页面的,可以使用模板语言来生成html元素,以及传递参数。

在templates新增index.html文件并写入以下代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% 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 %}
</body>
</html>

修改index方法

from django.shortcuts import render

from .models import Question


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

render()函数第一个位置参数是请求对象(view函数中第一个参数),第二个是参数模板(也就是这个方法会返回哪个页面),还有一个可选参数,一个字典形式传递给模板的数据

返回404错误

在views.py新增detail()函数

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'detail.html', {'question': question})

get_object_or_404()将一个Django模型作为第一个位置参数,后面可以跟任意个数的关键字参数,如果对象不存在,则会报Http404错误

在urls.py文件加入以下代码,配置请求

path('polls/<int:question_id>/', views.detail, name='detail'),

在templates新增detail.html文件并写入以下代码

{{ question }}

点击时,跳转页面会提示404

使用模板系统

在detail.html文件中写入以下代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
</body>
</html>

在模板系统中 .可以用它访问对象的属性。比如question.question_text

{% for %}for循环 上面代表表示将投票的选项全都循环出来,以列表展示

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值