Django实战(2)——Django视图初步(多个页面,超链接至另一个网页,基本的文本显示)

这是上一篇文章:https://blog.csdn.net/qq_41938259/article/details/96571765

它实现了网站的发布以及内网所有用户可以访问的要求,还有一个hello World页面。

这一篇博文主要讨论建立多张页面显示文本,从一张网页超链接至另一张。以一个投票网站为例。

  • 第一步

注释:polls/view.py文件和polls/urls文件分别的作用:view文件管理基本的视图,可以理解为是页面上看得见的东西。而urls则是管理地址栏键入的网址,而它们之间需要建立映射关系网站才会起效。

要添加跟多的视图/网页页面,点入polls/view.py 再写入代码:

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)

要使得这些视图起效,还要添加相应url映射,进入polls/urls.py文件:

from django.conf.urls import url

from . import views

urlpatterns = [
    # ex: /polls/
    url(r'^$', views.index, name='index'),
    # ex: /polls/5/
    url(r'^(?P[0-9]+)/$', views.detail, name='detail'),
    # ex: /polls/5/results/
    url(r'^(?P[0-9]+)/results/$', views.results, name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),
]

这里面运用了大量的正则表达式来匹配网页路径。后两个参数,意思是分别执行views里的detai,result,vote函数。第三个则是传入相应的name参数,实际上是用来告知view应当使用什么函数。

  • 第二步

polls 目录里创建一个 templates 目录。Django 将会在这个目录里查找模板文件。再在tenplates目录里建一个polls文件夹。这个新建的polls文件夹里存放html文件,这是用作模板的。

模板命名空间

虽然我们现在可以将模板文件直接放在 polls/templates 文件夹中(而不是再建立一个 polls 子文件夹),但这不是个好办法。Django 将会选择第一个匹配的模板文件,如果你有一个模板文件正好和另一个应用中的某个模板文件重名,Django 没有办法区分它们。我们需要 Django 选择正确的模板,最简单的方法就是把他们放入各自的命名空间中,也就是把这些模板放入一个和自身应用重名的子文件夹里

 在这个文件夹里创建一个名为index.html的文件,并键入如下代码:

{% if latest_question_list %}
    
{% else %}
    

No polls are available.

{% endif %}

接着在polls/view.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))

这时运行服务器,命令是python manage.py runserver 0.0.0.0:8000命令,再在浏览器里键入localhost:8000/polls就会看到一个what‘s new的文本,这个文本是上篇文章添加的。

「载入模板,填充上下文,再返回由它生成的 HttpResponse 对象」是一个如此常用的操作流程。于是 Django 提供了一个快捷函数,我们用它来重写 index() 视图:「载入模板,填充上下文,再返回由它生成的 HttpResponse 对象」是一个如此常用的操作流程。于是 Django 提供了一个快捷函数,我们用它来重写 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, 'polls/index.html', context)
  • 抛出404错误的一个快捷函数

这里有个新概念:如果指定问题 ID 所对应的问题不存在,这个视图就会抛出一个 Http404 异常。用 get() 函数获取对象,抛出 Http404错误」也是一个常用流程。Django 也提供了一个快捷函数,写在 detail() 视图里: 

from django.shortcuts import get_object_or_404, render

from .models import Question
# ...
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})
  • 使用模板系统

在新建的那个polls文件夹创建一个detail.html文件,写入如下代码:

{{ question.question_text }}

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

模板系统统一使用「点」符号来访问变量的属性。在示例 {{ question.question_text }} 中,首先 Django 尝试对 Question 对象使用字典查找(也就是使用obj.get(str)操作),如果失败了就尝试属性查找(也就是obj.str操作),结果是成功了。如果这一操作也失败的话,将会尝试列表查找(也就是obj[int]操作)。

{% for %} 循环中发生的函数调用: question.choice_set.all 被解释为 Python 代码 question.choice_set.all(),将会返回一个可迭代的 Choice 对象,这一对象可以在{% for %} 标签内部使用。

查看 模板指南 可以了解关于模板的更多信息。

 


  • 为 URL 名称添加命名空间

 答案是:在 URLconf 中添加命名空间。在 polls/urls.py 文件中添加 app_name 变量作为应用的命名空间:

polls/urls文件中添加这一行:

app_name = 'polls'

到这就差不多了,以下是完整代码:

view.py文件

from django.http import HttpResponse
from .models import Question
from django.template import loader
from django.shortcuts import get_object_or_404, render

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):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

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)

urls.py文件

from django.conf.urls import url

from . import views

app_name="polls"

urlpatterns = [
    # ex: /polls/
    url(r'^$', views.index, name='index'),
    # ex: /polls/5/
    url(r'^(?P[0-9]+)/$', views.detail, name='detail'),
    # ex: /polls/5/results/
    url(r'^(?P[0-9]+)/results/$', views.results, name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'),

    url(r'^specifics/(?P[0-9]+)/$', views.detail, name='detail'),
]

detail.html文件

{{ question.question_text }}

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

index.html文件

{% if latest_question_list %}
    
{% else %}
    

No polls are available.

{% endif %}

END

你可能感兴趣的:(Python的学习,Django框架的学习)