Django学习笔记04-视图和模板

视图

一个视图就是一个页面,提供特定的功能。在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)

Django学习笔记04-视图和模板_第1张图片

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

 

模板

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

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




    
    Title


{% if latest_question_list %}
    
{% else %}
    

No polls are available.

{% endif %}

修改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函数中第一个参数),第二个是参数模板(也就是这个方法会返回哪个页面),还有一个可选参数,一个字典形式传递给模板的数据

Django学习笔记04-视图和模板_第2张图片

 

返回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//', views.detail, name='detail'),

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

{{ question }}

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

 

使用模板系统

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




    
    Title


{{ question.question_text }}

    {% for choice in question.choice_set.all %}
  • {{ choice.choice_text }}
  • {% endfor %}

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

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

Django学习笔记04-视图和模板_第3张图片

你可能感兴趣的:(Django)