Django 入门学习总结4

news2024/9/25 23:16:32

视图是Django应用程序在Python语言中提供特定的方法并对应于有特定的模板的网页。网页的页面通过视图的方式进行跳转。

在投票系统中,有四个视图:

  • 首页视图,显示最新的问题列表。
  • 细节视图,显示问题文本,通过表单可以提交问题。
  • 结果视图,显示问题和对应的结果。
  • 投票跳转,管理一个问题对应于一个选项的投票跳转页面。

1、视图的产生

修改polls/views.py文件,增加视图相关内容。

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
        return HttpResponse("Hello, world. You're at the polls index.")
        
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.py文件中,以便跳转时使用。

在地址栏中输入:

http://127.0.0.1:8000/polls/34/

则在页面中显示:

You're looking at question 34.

输入http://127.0.0.1:8000/polls/34/results/,则显示:

You're looking at the results of question 34.

2、使用视图完成相应的工作

每个视图会返回包含的内容或输出异常。

修改polls/views.py文件,以便显示更详细的信息。

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)

这种方式为硬代码方式,每次修改网页的内容,需要修改Python代码。

可以通过模板的方式来显示网页的内容。

第一步,在polls中创建templates文件夹,Django会自动地从这个文件夹中寻找模板文件。在templates文件夹中创建polls文件夹,如下图所示。

新建polls/templates/polls/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文件中的index方法:

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))

这个方法将调用模块页面,并输出内容。这时再输入地址:

http://127.0.0.1:8000/polls/

将会显示投票系统列表页面。

Django提供了另一种快捷的方式,功能是一样的:

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)

3、处理404错误

继续修改polls/views.py文件如下:

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})

新建polls/templates/polls/detail.html文件内容如下:

4、使用模块系统

修改polls/templates/polls/detail.html内容为:

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

5、在模板中清除硬代码内容

修改polls/index.html内容:

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

6、URL命名空间的命名

在polls/urls.py文件中,添加一行语句:

app_name = "polls"

。。。

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/templates/polls/index.html文件中的内容为:

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

以体现命名空间的效果,最后的显示效果是一样的。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1243450.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【标注数据】labelme的安装与使用

这里写目录标题 下载标数据 下载 标数据 打开自动保存 创建矩形

FreeRTOS的并行与并发思考

FreeRTOS的任务触发是由滴答时钟触发SysTick中断来触发调度器执行或阻塞或挂起和切换任务的。 首先是任务的并发能力&#xff0c;FreeRTOS的任务执行是基于全抢占调度机制&#xff0c;任务优先级按在就绪列表中由高到低排布&#xff0c;系统首先执行最高优先级任务&#xff0c;…

【element优化经验】怎么让element-ui中表单多语言切换排版不乱

目录 前言&#xff1a; 痛点&#xff1a; 1.左对齐&#xff0c;右对齐在中文和外语情况下字数不同&#xff0c;固定宽度会使名称换行&#xff0c;不在整行对齐&#xff0c;影响美观。 2.如果名称和输入框不在一行&#xff0c;会使页面越来越长 3.label-width值给变量&#…

Switch的使用及其注意事项

注意第五点要看清&#xff0c;case执行完后匹配没有成功&#xff0c;如过有Default&#xff0c;将会执行Default&#xff0c;如果有case在Default之后&#xff0c;而且Default没有break语句&#xff0c;那么将会继续执行case的语句&#xff0c;此时case中的常量表达式只起语句标…

鸿蒙(HarmonyOS)应用开发——ArkTs学习准备

介绍 前面我们已经介绍了&#xff0c;如何安装HarmonyOS的IDE ,那么现在我们来介绍一下。HarmonyOS 开发的语言——ArkTs. ArkTS 是HarmonyOS的开发语言&#xff0c;他是typescript 的扩展&#xff0c;而typesrcipt是javascript的超集&#xff0c;如果你不太熟悉typescript语法…

fork介绍,返回值问题,写时拷贝,进程切换,子进程开始执行的位置,子进程的用途

目录 fork 介绍 fork的返回值问题 介绍 fork()时,系统要做什么 数据是否要独立 如果共享的话,就会出现问题! 写时拷贝 引入 介绍 举例(fork返回值) fork返回的值是什么 创建失败的原因 子进程执行位置从哪里开始 引入 进程切换 子进程执行的位置 子进程的…

SAP-部分字段变更

在SAP中部分字段是可以自行调整的&#xff0c;例如下图 这个字段是客户组1&#xff0c;已经被改成一级经理&#xff0c;现在来操作改回客户组1 首先选择字段点击F1-技术信息-数据元素&#xff08;双击&#xff09; . . 保存&#xff0c;返回&#xff0c;激活&#xff0c;返…

计算方法 期末总结

思维导图 绪论 算法的性质&#xff1a; 有穷性、确切性、有输入输出、可行性 算法的描述方法&#xff1a; 自然语言、伪代码、流程图、N-S流程图 算法设计思想&#xff1a; 化大为小的缩减技术&#xff1a;二分法化难为易的校正技术&#xff1a;开方法化粗为精的松弛技术&a…

听GPT 讲Rust源代码--src/tools(2)

题图来自AI生成 File: rust/src/tools/rust-installer/src/util.rs 在Rust源代码中&#xff0c;rust/src/tools/rust-installer/src/util.rs文件是安装程序的一个辅助文件&#xff0c;它提供了一些实用函数和结构体来处理安装过程中需要的一些操作。 这个文件中定义了几个结构体…

本地websocket服务端暴露至公网访问【cpolar内网穿透】

本地websocket服务端暴露至公网访问【cpolar内网穿透】 文章目录 本地websocket服务端暴露至公网访问【cpolar内网穿透】1. Java 服务端demo环境2. 在pom文件引入第三包封装的netty框架maven坐标3. 创建服务端,以接口模式调用,方便外部调用4. 启动服务,出现以下信息表示启动成功…

香港科技大学广州|先进材料学域博士招生宣讲会—华中科技大学大学专场!!!(暨全额奖学金政策)

“跨学科融合创新&#xff0c;引领新兴与未来行业的突破与发展——先进材料学域” 世界一流的新型可持续材料创新研究 夯实的先进材料领域国际学术影响力 教授亲临现场&#xff0c;面对面答疑解惑助攻申请&#xff01; 一经录取&#xff0c;享全额奖学金1.5万/月&#xff01; …

力扣:178. 分数排名(Python3)

题目&#xff1a; 表: Scores ---------------------- | Column Name | Type | ---------------------- | id | int | | score | decimal | ---------------------- 在 SQL 中&#xff0c;id 是该表的主键。 该表的每一行都包含了一场比赛的分数。Score …

力扣236. 二叉树的最近公共祖先(java DFS解法)

Problem: 236. 二叉树的最近公共祖先 文章目录 题目描述思路解题方法复杂度Code 题目描述 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为&#xff1a;“对于有根树 T 的两个节点 p、q&#xff0c;最近公共祖先表示为一个节点 x&am…

3、如何从0到1去建设数据仓库

1、数仓实施过程 1.1 数据调研 数据调研包括&#xff1a;业务调研、需求调研 业务调研 需要调研企业内有哪些业务线、业务线的业务是否还有相同点和差异点 各个业务线有哪些业务模块&#xff0c;每个模型下有哪些业务流程&#xff0c;每个流程下产生的数据 是怎样存储的 业务调…

5.1 PBR基础 BRDF介绍

基于物理的渲染&#xff08;Physically Based Rendering&#xff0c;PBR&#xff09;是指使用基于物理原理和微平面理论建模的着色/光照模型&#xff0c;以及使用从现实中测量的表面参数来准确表示真实世界材质的渲染理念。 一、反射率方程 理论基础放在参考链接里。 直接开始…

登陆页面模板

简单好看的登陆页面 vue项目代码 可忽略js部分 先来个效果图 <template><div class"login"><div class"content"><p >账户密码登录</p><div class"unit"><label class"label">用户名</…

Vocoder,声码器详解——语音信号处理学习(十)

参考文献&#xff1a; [1] Vocoder (由助教許博竣同學講授)哔哩哔哩bilibili [2] Oord A, Dieleman S, Zen H, et al. Wavenet: A generative model for raw audio[J]. arXiv preprint arXiv:1609.03499, 2016. [3] https://deepmind.com/blog/article/wavenet-generative-mode…

【数据结构/C++】线性表_双链表基本操作

#include <iostream> using namespace std; typedef int ElemType; // 3. 双链表 typedef struct DNode {ElemType data;struct DNode *prior, *next; } DNode, *DLinkList; // 初始化带头结点 bool InitDNodeList(DLinkList &L) {L (DNode *)malloc(sizeof(DNode))…