django 搭建一个投票类网站(三)

  之前修改index的视图的代码,工作原理是先试用loader方法加载视图,然后HTTPResponse方法初始化一个HTTPResponse对象并返回给浏览器。对于很多django视图来说,他们的工作原理是这样的,因此django写了一个简写函数render。下面使用render函数重写index视图,

from django.shortcuts import render

from django.http import HttpResponse

from .models import Question

from django.template import loader

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

  然后重新访问index,会发现什么都没发生变化。

  引用render包之后,代码中讲不需要loader和HttpResponse包

1.处理404错误

  404错误一般是跳转时页面不存在时所显示的错误。下面修改detail视图使其在被查找的问卷不存在时抛出404错误,在polls/views输入以下代码

from django.shortcuts import render

from django.http import Http404

from .models import Question

def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("问卷不存在")
    return render(request, 'polls/detail.html' , {'question': question})

   然后重启web服务,访问一个不存在的问卷,比如http://127.0.0.1:8000/polls/10,然后会显示这样的界面

  由于404错误也是一个非常常见的网络异常,所以django也提供了一个简写方法:get_object_or_404。也可以用这个方法来修改detail视图

2.使用模板系统

  前面的模板过于简单,现实中django的模板系统十分强大。下面创建一个detail.html,然后复制以下代码到这里面

<h1>{{ question.question_text }}</h1>
<ul>
    {% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
    {% endfor %}
</ul>

  (解释下这段代码,{%%}这种新式的代码是django模板语言中的函数语法,for choice这条就是一个for循环,循环对象是question.choice_set.all,该对象等价于python中的question.choice_set.all,返回一个可遍历数组,然后对应的要在结尾上加上{%endfor%}表示循环结束)

  然后输入正确的url可以看到,对应的问卷名字被加粗显示出来了

·

  在index.html文件里,我们用硬编码的形式,编写了html超链接(<a href="/polls/{{question.id}}/">{{question.question_text }}</a>)。当项目有很多模板,并且多个模板都使用了同一个url时,那么这种url书写方式在修改时会带来很多不必要的工作量,不过可以通过url的命名方式改解决这个问题

  url中的代码是这样的path('<int:question_id>',views.detail, name='detail'),然后修改html里的代码,改成这样<a href=" {% url 'detail' question.id %}">{{question.question_text }}</a>

   其中{%url%}是django里的模板标签,用于定义url。该标签会在polls/urls模块中查询detail的url,如果需要传递多个参数,只要在question.id后面紧跟一个空格然后继续添加参数即可

  可是当存在很多detail视图的时候该怎么分辨呢,可以为url添加命名空间的方式解决问题。

  在polls/urls下修改代码,添加app_name参数

  然后修改index.html里的内容

原文地址:https://www.cnblogs.com/afei123/p/11253354.html