首页 > 编程语言 >编写你的第一个 Django 应用程序,第3部分

编写你的第一个 Django 应用程序,第3部分

时间:2023-04-18 21:59:31浏览次数:50  
标签:index polls question detail 视图 Django 应用程序 编写 模板

本教程从教程 2 停止的地方开始。我们是 继续网络投票应用程序,并将专注于创建公众界面 – “视图”。

在我们的投票应用程序中,我们将有以下四个视图:

  • 问题“索引”页面 – 显示最新的几个问题。
  • 问题“详细信息”页面 – 显示问题文本,没有结果,但 用表格投票。
  • 问题“结果”页面 – 显示特定问题的结果。
  • 投票操作 – 处理对特定选项的投票 问题。

一、写入更多视图

现在,让我们再向 polls/views.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)

通过添加这些新视图到 polls.urls  以下  path()调用将连接到模块中:

from django.urls import path

from . import views

urlpatterns = [
    # ex: /polls/
    path("", views.index, name="index"),
    # ex: /polls/1/
    path("<int:question_id>/", views.detail, name="detail"),
    # ex: /polls/1/results/
    path("<int:question_id>/results/", views.results, name="results"),
    # ex: /polls/1/vote/
    path("<int:question_id>/vote/", views.vote, name="vote"),
]

启动服务后,就可以访问浏览器了 url地址 :  /polls/1/ ;  /polls/1/results/ ;  /polls/1/vote/

二、编写实际执行某些操作的视图

from django.http import HttpResponse

from .models import Question


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)


# Leave the rest of the views (detail, results, vote) unchanged

但是,这里有一个问题:页面的设计在视图中是硬编码的。如果 你想改变页面的外观,你必须编辑这个Python代码。

因此,让我们使用 Django 的模板系统将设计与 Python 分开 创建视图可以使用的模板。

首先,在 polls 下 创建一个 templates 目录,Django 会在那里寻找模板,在 templates 目录下 再创建一个   polls 目录

然后创建一个html文件: index.html.也就是说你的模版文件在这个路径: polls/templates/polls/index.html

将以下代码放入该模板 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 %}

现在,让我们更新视图  polls/views.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 的字典 对象。polls/index.html

通过将浏览器指向“/polls/”来加载页面,您应该会看到一个 包含教程 2 中的 “What’s up”问题的项目符号列表。该链接指向问题的详细信息页面。

三、一个快捷方式:render()

加载模板、填充上下文并返回带有渲染结果的 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 错误

现在,让我们处理问题详细信息视图 - 显示问题文本的页面 对于给定的民意调查。这是视图

from django.http import Http404
from django.shortcuts import render

from .models import Question


# ...
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, "polls/detail.html", {"question": question})

这里的新概念:视图引发 Http404 异常 如果不存在具有请求 ID 的问题。

我们将讨论您可以在该模板 polls/detail.html 中放入的内容 稍后,但如果您想快速让上面的示例工作,请提供一个文件 仅包含:

{{ question }}

六、快捷键:get_object_or_404()

如果对象不存在,使用 get() 并引发 Http404 是一个非常常见的习惯用法。姜戈 提供快捷方式。这是重写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})

get_object_or_404() 函数采用 Django 模型 作为它的第一个参数和任意数量的关键字参数,它 传递给 get() 函数 模特的经理。如果对象没有,它会引发 Http404 存在。

还有一个 get_list_or_404() 函数,它可以工作 就像 get_object_or_404() 一样 – 除了使用 filter() 而不是 get()。如果列表为空,它将引发 Http404

七、使用模板系统

返回到detail()我们的投票应用程序的视图。鉴于上下文 question 变量,这是模板可能的样子 喜欢:polls/detail.html

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

模板系统使用点查找语法来访问变量属性。在 的例子,首先 Django 做字典查找 在对象上。如果做不到这一点,它会尝试属性查找 - 这 在这种情况下,有效。如果属性查找失败,它将尝试 列表索引查找。{{ question.question_text }}question

方法调用发生在 {% for %} 循环中:被解释为 Python 代码,它返回对象的可迭代对象,并且 适合在 {% for %} 标记中使用。

八、删除模板中的硬编码网址

请记住,当我们在模板中编写指向问题的链接时,链接是部分硬编码的,如下所示:polls/index.html

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

这种硬编码、紧密耦合方法的问题在于它变成了 在具有大量模板的项目上更改 URL 具有挑战性。然而,由于 您在 的 path() 函数中定义了 name 参数 该模块,您可以消除对特定 URL 路径的依赖 使用模板标记在 URL 配置中定义:polls.urls{% url %}

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

其工作方式是查找模块中指定的 URL 定义。您可以准确看到“详细信息”的URL名称在哪里 定义如下:polls.urls

...
# the 'name' value as called by the {% url %} template tag
path("<int:question_id>/", views.detail, name="detail"),
...

九、命名空间 URL 名称

教程项目只有一个应用程序polls .在真实的 Django 项目中, 可能有五个、十个、二十个或更多应用程序。Django 如何区分 它们之间的 URL 名称?例如polls,应用具有detail视图,博客的同一项目上的应用也可能具有视图。如何 让 Django 知道在使用模板标签时要为 URL 创建哪个应用程序视图?{% url %}

答案是将命名空间添加到您的 URLconf。在文件polls/urls.py中,继续并添加一个 app_name 以设置应用程序命名空间:

from django.urls import path

from . import views

app_name = "polls"
urlpatterns = [
    path("", views.index, name="index"),
    path("<int:question_id>/", views.detail, name="detail"),
    path("<int:question_id>/results/", views.results, name="results"),
    path("<int:question_id>/vote/", views.vote, name="vote"),
]

现在将您的模板从:polls/index.html

polls/templates/polls/index.html
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

指向命名空间详细信息视图:

polls/templates/polls/index.html
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

当您熟悉编写视图时,请阅读本教程的第 4 部分,了解有关表单处理和泛型的基础知识 视图。

----------------------------------------------end----------------------------------------------

 

标签:index,polls,question,detail,视图,Django,应用程序,编写,模板
From: https://www.cnblogs.com/xh2023/p/17331234.html

相关文章

  • django4.0 项目集成 xadmin 后台管理
    Djangoxadmin是Django框架的一个第三方应用程序,它提供了许多基于Web的界面来管理您的Django应用程序。1.安装xadmin  pipinstallhttps://github.com/sshwsfc/xadmin/tarball/master 如果你的django版本过高,和我一样是使用的4.0,会出现不兼容等,多种报错。 请将下......
  • Docker快速入门 三(dockerfile常用命令,dockerfile构建django项目,docker私有仓库,docker-
    目录Docker一、Dcokerfile常用命令二、Dockerfile构建Django项目三、Docker私有仓库1、简介2、镜像传到官方仓库3、镜像分层4、搭建私有仓库四、Docker-conpose1、Docker-conpose部署项目1、新建flask项目2、编写dockerfile3、编写docker-conpose的yml文件4、启动docker-compoes2......
  • 小白用chatgpt编写python 爬虫程序代码 抓取网页数据(js动态生成网页元素)
    jS动态生成,由于呈现在网页上的内容是由JS生成而来,我们能够在浏览器上看得到,但是在HTML源码中却发现不了一、注意:代码加入了常规的防爬技术    如果不加,如果网站有防爬技术,比如频繁访问,后面你会发现什么数据都取不到1.1 模拟请求头: 这里入进入一步加强,随机,主要是User-Agen......
  • Django视图类中标准导出Excel文件模版(自用)
    一、导出基类、Excel文件处理和保存importhashlibimportosimporttimeimportxlsxwriterfromapplicationimportsettingsfromapps.web.op_drf.filtersimportDataLevelPermissionsFilterfromapps.web.op_drf.responseimportSuccessResponsefromapps.web.wsys......
  • shell 编写脚本的一些细节心得:流程控制
    流程控制用得最多的,无非也就是老三样,if、for、while。if其中if作为判断的函数使用,其中也是有很多小细节的。例如你要判断两个值是否相等的时候,有两种方式,代码如下:test=2if((${test}==2))thenecho"yes"fiif[${test}-eq2]thenecho"yes"fi其实两段代码的......
  • imx6ul 编写中断程序步骤
    ①、启动文件start.s需要添加一级中断向量表和中断处理函数的框架两部分的内容。一级中断向量表如下:3_start:4ldrpc,=Reset_Handler/*复位中断*/5ldrpc,=Undefined_Handler/*未定义指令中断*/6ldrpc,=SVC_Handler/*SVC(Supervisor)中断*/7ldrpc,......
  • Python Django 模板的使用
    新建templates/header.html文件<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>header</title></head><body><h1>东营职业学院</h1><p>......
  • Django中TruncMonth截取日期使用方法,按月统计
    将原来的年月日按照月份来截取统计数据,具体参考如下官方示例:-官方提供fromdjango.db.models.functionsimportTruncMonthArticle.objects.annotate(month=TruncMonth('timestamp'))#Truncatetomonthandaddtoselectlist.values('month')#GroupBymonth.anno......
  • Shell之bash脚本的编写
    下面是我写的一段部署脚本。#!/bin/bashcontainerID=`dockerps|grepkapok-admin|awk'{print$1}'`dockerstop$containerIDecho"dockerstop$containerID"imageID=`dockerimages|grepkapok-admin|awk'{print$3}'`foridin$im......
  • 功能不够用?使用C++编写通达信插件及接入Python(二)
    参考:https://zhuanlan.zhihu.com/p/613157262一、准备工作(参考上一篇)安装VS2019 安装pycharm下载 http://help.tdx.com.cn/book.asp《通达信DLL函数编程规范.rar》二、下载python3.x的32位版本,http://www.python.org,随便找个32位版就行了。我准备下载Windowsembeddabl......