Django 8 通用视图基础

news2025/6/9 15:13:12

1. 什么是通用视图 

1. 在terminal 输入 django-admin startapp the_12回车

2. tutorial\settings.py 注册 

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "the_3",
    "the_5",
    "the_6",
    "the_7",
    "the_8",
    "the_9",
    "the_10",
    "the_12",
]

3.  tutorial\urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('the_3/', include('the_3.urls')),
    path('the_4/', include('the_4.urls')),
    path('the_5/', include('the_5.urls')),
    path('the_7/', include('the_7.urls')),
    path('the_10/', include('the_10.urls')),
    path('the_12/', include('the_12.urls')),
]

4. the_12\views.py

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

# Create your views here.

class Chello(View):
    def get(self,request):
        return JsonResponse({"python": '这是一个get方法'})

    def post(self,request):
        return JsonResponse({"python": '这是一个post方法'})

5. the_12\urls.py 

from django.urls import path
from .views import Chello

urlpatterns = [
    path('index/', Chello.as_view()),
]

6. 运行tutorial, 点击http://127.0.0.1:8000/,地址栏 127.0.0.1:8000/the_12/index/ 刷新 

 

7. 回到the_12\urls.py, 看as_view的源码(ctrl + 点鼠标左键)

2.使用通用视图的tips

  • 提供了什么功能
  • 数据从哪里来
  • 提供了哪些模板变量
  • 渲染的模板页

3.ListView 的使用 

  • 如何自定义获取到的列表对象的名字
  • 如何确定渲染的模板名字
  • 如何分页展示

1. the_12\models.py 

from django.db import models

# Create your models here.

class SomeThing(models.Model):
    msg = models.CharField(max_length=200)
    is_delete = models.BooleanField()

2. 迁移, terminal 输入 python .\manage.py makemigrations回车

Migrations for 'the_12':
  the_12\migrations\0001_initial.py
    - Create model SomeThing

3. terminal 输入 python .\manage.py migrate回车 

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, the_10, the_12, the_6, the_8, the_9
Running migrations:
  Applying the_12.0001_initial... OK

4. the_12\admin.py 

from django.contrib import admin
from the_12.models import SomeThing

# Register your models here.

admin.site.register(SomeThing)

5. 浏览器 http://127.0.0.1:8000/admin在SomeThing添加5条数据 

6. the_12\views.py 添加以下代码

class MyListView(ListView):
    pass

7. the_12\urls.py 

from django.urls import path
from .views import Chello,MyListView

urlpatterns = [
    path('index/', Chello.as_view()),
    # path 的第二个参数应该是一个函数,as_view就是把Chello这个类变成函数
    path('mylist/', MyListView.as_view()),
]

8. 浏览器 ImproperlyConfigured at /the_12/mylist/

9. the_12\views.py 

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django.views.generic import ListView
from .models import SomeThing

# Create your views here.

class Chello(View):
    def get(self,request):
        return JsonResponse({"python": '这是一个get方法'})

    def post(self,request):
        return JsonResponse({"python": '这是一个post方法'})

class MyListView(ListView):
    model = SomeThing

10. 刷新网页 

11. 在templates创建the_12文件夹,再在新创建的the_12文件夹内创建一个something_list。html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>这是something_list的页面</h1>
</body>
</html>

12. 刷新网页 

13. templates\the_12\something_list.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>这是something_list的页面</h1>
    <ul>
        {% for i in object_list %}
        <li>{{ i.msg }}</li>
        {% endfor %}
    </ul>
</body>
</html>

14. 刷新网页 

15. 总结 

"""
提供了什么功能
    以列表的形式展示数据的功能
数据从哪里来
    数据从数据库中查询得来的
    model
    queryset
    get_queryset
提供了哪些模板变量
    object_list
    自定义 : context_object_name
    something_list
渲染的模板页
    默认
    模型名的小写_list.html
    自定义:template_name
"""

the_12\views.py 

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django.views.generic import ListView
from .models import SomeThing

# Create your views here.

class Chello(View):
    def get(self,request):
        return JsonResponse({"python": '这是一个get方法'})

    def post(self,request):
        return JsonResponse({"python": '这是一个post方法'})

class MyListView(ListView):
    # model = SomeThing
    # queryset = SomeThing.objects.all()
    def get_queryset(self):
        queryset = SomeThing.objects.filter(is_delete=0)
        return queryset

    context_object_name = 'panda'
    template_name = 'the_12/huahua.html'

templates\the_12\something_list.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>这是something_list的页面</h1>
    <ul>
        {% for i in object_list %}
        <li>{{ i.msg }}</li>
        {% endfor %}
    </ul>
</body>
</html>

templates\the_12\huahua.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>这是huahua的页面</h1>
    <ul>
        {% for i in object_list %}
        <li>{{ i.msg }}</li>
        {% endfor %}
    </ul>
</body>
</html>

16. 分页操作 , the_12\views.py

class MyListView(ListView):
    paginate_by = 2

templates\the_12\huahua.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>这是huahua的页面</h1>
    <ul>
        {% for i in object_list %}
        <li>{{ i.msg }}</li>
        {% endfor %}
    </ul>
    {% for page in paginator %}
        <a href="">{{ page.number }}</a>
    {% endfor %}
</body>
</html>

刷新网页 

17. the_12\urls.py, 做以下更改 

path('mylist/', MyListView.as_view(),name='something')

18. templates\the_12\huahua.html 

{% for page in paginator %}
        <a href="{% url 'something' %}">{{ page.number }}</a>
    {% endfor %}

相当于 templates\the_12\huahua.html

{% for page in paginator %}
    <a href="{% url 'something' %}?page={{ page.number }}">{{ page.number }}</a>
{% endfor %}

19. 源码分析 

class MyListView(ListView):
class ListView(MultipleObjectTemplateResponseMixin, BaseListView):
class MultipleObjectTemplateResponseMixin(TemplateResponseMixin):

        the_12/something_list.html

        自定义了模板名,供程序使用

class TemplateResponseMixin:  

        主要的作用是找到模板的名字,然后渲染上下文数据

class BaseListView(MultipleObjectMixin, View):

        重写了get方法

class MultipleObjectMixin(ContextMixin):    
        queryset = None
        model = None
        paginate_by = None
        paginate_orphans = 0
        context_object_name = None

4.常见通用视图可自定义属性

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

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

相关文章

权威外媒聚焦:Messari强调波场TRON在全球加密支付领域的引领作用

近日,金融时报、费加罗报及美联社等海外权威媒体就波场TRON 在全球加密支付领域的重要进展发布了相关报道。报道引述加密研究机构Messari 《Crypto Theses for 2024》年度报告,重点强调了波场TRON在推动全球加密货币支付尤其是稳定币USDT应用方面的显著成就。 报道提到,波场TR…

【LeetCode:114. 二叉树展开为链表 | 二叉树 + 递归】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

Vue3+Typescript+setup / Vue2使用scrollIntoView()实现锚点跳转指定列表

在标签上添加ref属性来引用DOM元素&#xff0c; Vue2中使用$refs来获取该DOM元素并调用scrollIntoView()方法。 使用ref"yearDiv"在每个年份的div元素上添加了一个引用。然后&#xff0c;在yearClick方法中&#xff0c;我们通过this.$refs.yearDiv[year]来获取对应…

HTML5-新增表单input属性

新增表单属性 form控件主要新增的属性: autocomplete 是否启用表单的自动完成功能&#xff0c;取值&#xff1a;on&#xff08;默认&#xff09;、off novalidate 提交表单时不进行校验&#xff0c;默认会进行表单校验 autocomplete属性 概念&#xff1a;autocomplete属性…

Ontrack EasyRecovery(易恢复中国)2024专业数据文件恢复软件

Ontrack EasyRecovery(易恢复中国)是全球著名数据厂商Kroll Ontrack出品的一款专业数据文件恢复软件.EasyRecovery数据恢复软件支持恢复不同存储介质数据:硬盘,光盘,U盘/移动硬盘,数码相机,RAID磁盘阵列数据恢复修复等,EasyRecovery中文版可以恢复被删除或丢失的包括文档,表格,…

nodejs-day1——模块、第三方包管理

自定义模块 我们创建的每个JS文件都是一个自定义模块&#xff0c;并且具有模块作用域&#xff0c;也就是在一个模块中创建的变量、常量、函数等等一切&#xff0c;都只能在当前模块中使用 优点&#xff1a; 1.共享&#xff08;导出/暴露&#xff09;内容给其它模块用&#x…

rabbitmq延时队列相关配置

确保 RabbitMQ 的延时消息插件已经安装和启用。你可以通过执行以下命令来安装该插件&#xff1a; rabbitmq-plugins enable rabbitmq_delayed_message_exchange 如果提示未安装&#xff0c;以下是安装流程&#xff1a; 查看mq版本&#xff1a; 查看自己使用的 MQ&#xff08;…

基于B/S架构的数字孪生智慧监所可视化监管系统

1 前言 物联网技术的发展使云计算技术得到了迅猛的发展及广泛的应用&#xff0c;智能体系的创建已经成为监狱发展的必然趋势。 智慧监狱的创建、智能化管理的推行是监狱管理的创新&#xff0c;也是监狱整体工作水平提升的具体体现。 1.1 建设背景 近年来&#xff0c;司法部不…

数字孪生与边缘计算的结合

数字孪生与边缘计算的结合可以在物理实体附近进行实时数据处理和决策&#xff0c;从而提高响应速度、降低延迟&#xff0c;并有效地利用边缘资源。以下是数字孪生在边缘计算中的一些应用&#xff0c;希望对大家有所帮助。北京木奇移动技术有限公司&#xff0c;专业的软件外包开…

天津最新web前端培训班 如何提升web技能?

随着互联网的迅猛发展&#xff0c;web前端成为了一个热门的职业方向。越来越多的人希望能够通过学习web前端技术来提升自己的就业竞争力。为了满足市场的需求&#xff0c;许多培训机构纷纷推出了web前端培训课程。 什么是WEB前端 web前端就是web给用户展示的东西&#xff0c;…

sqlserver把Long类型的时间转换为可视化的时间

SqlServer 把Long类型日期还原yyyy-MM-dd HH:mm:ss格式日期&#xff1a; SELECT CONVERT(DATETIME, Dateadd(second, 1704330940847 / 1000, 19700101 08:00), 111) AS tt SqlServer 把Long类型日期还原yyyy-MM-dd格式日期&#xff1a; SqlServer中&#xff0c;按照UTC计算标准…

MATLAB对数据的处理(导入,异常处理)

MATLAB对数据的处理 文章目录 MATLAB对数据的处理1、MATLAB导入数据导入的范围导入类型 2、MATLAB处理缺失值和异常值 1、MATLAB导入数据 最常用的就是导入excel表格数据&#xff0c;主页选项卡-导入数据-选择excel文件。 导入的范围 导入数据的范围默认是从第二行开始的&am…

增删改查语句实现了解不同的函数与特殊字符unionunion all区别

一、crud&#xff08;增删改查&#xff09; 1.1、查询 概念&#xff1a; 查询数据是指从数据库中根据需求&#xff0c;使用不同的查询方式来获取不同的数据&#xff0c;是使用频率最高、最重要的操作 注&#xff1a;在MySQL中&#xff0c;当执行一条SQL语句后&#xff0c;系…

【栈越界】变量未赋值前提下,值却发生改变??

首先&#xff0c;提出2个问题&#xff1a; 数组越界 和 栈越界是一回事吗&#xff1f;以上两种越界若有发生&#xff0c;程序一定会跑飞吗&#xff1f; 目录 1. 一个栈越界的例子2. 程序的内存分部3. RAM 空间示意图 1. 一个栈越界的例子 创建 STM32 工程并写了一段测试代码 …

通往人工智能的 Go 之路

Agency 该库旨在为那些希望通过清晰、高效且符合 Go 语言惯例的方法来探索大型语言模型&#xff08;LLMs&#xff09;和其他生成式人工智能的开发人员而设计。 特点 纯 Go 语言&#xff1a;快速、轻量级&#xff0c;静态类型&#xff0c;无需涉及 Python 或 JavaScript编写清晰…

P1423 小玉在游泳python

s float(input()) sum 0 step 0 meter 2.0 while sum < s:sum metermeter 0.98 * meterstep 1 print(step)

图像分割-Grabcut法(C#)

版权声明&#xff1a;本文为博主原创文章&#xff0c;转载请在显著位置标明本文出处以及作者网名&#xff0c;未经作者允许不得用于商业目的。 本文的VB版本请访问&#xff1a;图像分割-Grabcut法-CSDN博客 GrabCut是一种基于图像分割的技术&#xff0c;它可以用于将图像中的…

使用生成式AI查询大型BI表

在拥有大量表格形式数据的组织中&#xff0c;数据分析师的工作是通过提取、转换和围绕数据构建故事来理解这些数据。 分析师访问数据的主要工具是 SQL。 鉴于大型语言模型 (LLM) 令人印象深刻的功能&#xff0c;我们很自然地想知道人工智能是否可以帮助我们将信息需求转化为格式…

事实就是这么残酷,分享一个案例投资者是怎么一步步失败

都说交易市场要学会斗智斗勇&#xff0c;但fpmarkets澳福提醒交易者要始终记住&#xff0c;买的没有卖的精&#xff0c;下面就分享一个案例&#xff0c;让各位投资者知道现实就是这么残酷&#xff0c;一些无良的资本是怎么一步步让投资者失败的。 当在整个交易市场中渐渐地&am…

基于spring boot物流管理系统设计与实现

&#x1f345;点赞收藏关注 → 私信领取本源代码、数据库&#x1f345; 本人在Java毕业设计领域有多年的经验&#xff0c;陆续会更新更多优质的Java实战项目希望你能有所收获&#xff0c;少走一些弯路。&#x1f345;关注我不迷路&#x1f345;一 、设计说明 1.1 课题背景及意…