目录

Django 9 常用通用视图分析

View

提供基于不同http方法执行不同逻辑的功能。

  1. 创建 terminal输入 django-admin startapp the_13回车

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",
    "the_13",
]
  1. 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')),
    path('the_13/', include('the_13.urls')),
]
  1. the_13\views.py
python 复制代码
from django.shortcuts import render
from django.views import View


# Create your views here.

class Hello(View):
    pass

ctrl + 鼠标左键 点击 View可以看源码里面的View方法 。

as_view方法里面重写了view方法,这个view方法返回dispatch功能,通过dispatch功能的分发方法,然后去method方法中看到对应的方法有get,post等方法,views.py 里面的hello就可以执行对应的get或者post方法

TemplateView

基于View之上针对get方法提供了渲染特定模板的功能。

  1. the_13\views.py 添加 class TemplateTest(TemplateView):

  2. ctrl + 鼠标左键点击TemplateView

复制代码
class TemplateView(TemplateResponseMixin, ContextMixin, View):
    """
    Render a template. Pass keyword arguments from the URLconf to the context.
    """
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

可以看到 TemplateView 继承了 TemplateResponseMixin, ContextMixin, View。

复制代码
class TemplateResponseMixin:
    """A mixin that can be used to render a template."""
    template_name = None
    template_engine = None
    response_class = TemplateResponse
    content_type = None
  1. templates文件夹创建子文件夹 the_13, 再在新建的the_13文件夹创建panda.html, panda.html的代码
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>panda</title>
</head>
<body>
    <h1>这是TemplateView的页面</h1>
</body>
</html>
  1. the_13\views.py
python 复制代码
from django.shortcuts import render
from django.views import View
from django.views.generic import TemplateView


# Create your views here.

class Hello(View):
    pass

class TemplateTest(TemplateView):
    template_name = 'the_13/panda.html'
复制代码
TemplateResponseMixin ---> 提供了找到模板名然后渲染模板的能力
复制代码
class ContextMixin:
    """
    A default context mixin that passes the keyword arguments received by
    get_context_data() as the template context.
    """
    extra_context = None

    def get_context_data(self, **kwargs):
        kwargs.setdefault('view', self)
        if self.extra_context is not None:
            kwargs.update(self.extra_context)
        return kwargs
复制代码
ContextMixin ---> 帮我们获取上下文的能力
  1. the_13\views.py
python 复制代码
from django.shortcuts import render
from django.views import View
from django.views.generic import TemplateView


# Create your views here.

class Hello(View):
    pass

class TemplateTest(TemplateView):
    template_name = 'the_13/panda.html'

    def get_context_data(self, **kwargs):
        context = super(TemplateTest,self).get_context_data()
        context['lan'] = 'python-django'
        return context
  1. the_13\urls.py
python 复制代码
from django.urls import path
from .views import TemplateTest

urlpatterns = [
    path('template_test/', TemplateTest.as_view()),
]
  1. 运行tutorial, 点击http://127.0.0.1:8000/, 浏览器地址栏 panda, 刷新浏览器
  1. templates\the_13\panda.html body 里面添加 {{ lan }}
复制代码
<body>
    <h1>这是TemplateView的页面</h1>
    {{ lan }}
</body>
  1. 刷新浏览器

TemplateView总结

  • 提供了什么功能: 在view的基础上,针对get方法, 渲染指定模板的功能
  • 数据从哪里来: 没数据 ---- get_context_data
  • 提供了哪些模板变量 没提供
  • 渲染的模板页 template_name 自定义

RedirectView

基于View之上, 提供了重定向的功能

  • permanent
  • url
  • pattern_name
  1. the_13\views.py
python 复制代码
from django.shortcuts import render
from django.views import View
from django.views.generic import TemplateView, RedirectView


# Create your views here.

class Hello(View):
    pass

class TemplateTest(TemplateView):
    template_name = 'the_13/panda.html'

    def get_context_data(self, **kwargs):
        context = super(TemplateTest,self).get_context_data()
        context['lan'] = 'python-django'
        return context

    # def post(self):
    #     pass

"""
render(request,'模板', {"lan":"python-django"})
"""

class RedirectTest(RedirectView):
    url = '/the_10/index/'
  1. the_13\urls.py
python 复制代码
from django.urls import path
from .views import TemplateTest,RedirectTest

urlpatterns = [
    path('template_test/', TemplateTest.as_view()),
    path('redirect_test/', RedirectTest.as_view()),
]
  1. 运行tutorial, 点击 http://127.0.0.1:8000/

浏览器地址栏 http://127.0.0.1:8000/the_13/redirect_test/ 刷新

  1. pattern_name, 在 the_10\urls.py
python 复制代码
from django.urls import path
from .views import index

urlpatterns = [
    path('index/', index, name='hua'),
]
  1. the_13\views.py
python 复制代码
class RedirectTest(RedirectView):
    # url = '/the_10/index/'
    pattern_name = 'hua'
  1. 运行 tutorial, 点击http://127.0.0.1:8000/ , 浏览器地址栏 http://127.0.0.1:8000/the_13/redirect_test/ 刷新

源码分析 :

复制代码
permanent = False   是否永久重定向
url = None
pattern_name = None   url中name参数
query_string = False

RedirectView总结

  • 提供了什么功能: 基于View之上提供重定向的功能
  • 数据从哪里来: url pattern_name
  • 提供了哪些模板变量 没提供
  • 渲染的模板页 没渲染

通用视图分析法

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

ListView

提供以(分页)列表形式展示一个(或多个关联)数据库表的功能

  • queryset、model、get_queryset
  • paginate_by、page
  • context_object_name
  • template_name
复制代码
提供了什么功能
    以列表的形式展示数据的功能
数据从哪里来
    数据从数据库中查询得来的
    model
    queryset
    get_queryset
提供了哪些模板变量
    object_list
    自定义 : context_object_name
    something_list
渲染的模板页
    默认
    子应用名/模型名的小写_list.html
      the_12的ListViews类使用的是the_10的模型
      请问模板渲染 渲染的是the_12的模板还是the_10的模板
       回答: the_10的, 模型在哪里,渲染的应用就在哪里

    自定义:template_name

Mixins

从ListView入手分析混入

混入可以继承多个,但是View只能继承一个

DetailView

  • template_name_suffix
  • object
  1. the_13\views.py
python 复制代码
from django.shortcuts import render
from the_12.models import SomeThing
from django.views import View
from django.views.generic import TemplateView, RedirectView, ListView, DetailView


# Create your views here.

class Hello(View):
    pass

class TemplateTest(TemplateView):
    template_name = 'the_13/panda.html'

    def get_context_data(self, **kwargs):
        context = super(TemplateTest,self).get_context_data()
        context['lan'] = 'python-django'
        return context

    # def post(self):
    #     pass

"""
render(request,'模板', {"lan":"python-django"})
"""

class RedirectTest(RedirectView):
    # url = '/the_10/index/'
    pattern_name = 'hua'

class DetailViewTest(DetailView):
    model = SomeThing
  1. the_13\urls.py
python 复制代码
from django.urls import path
from .views import TemplateTest,RedirectTest,DetailViewTest

urlpatterns = [
    path('template_test/', TemplateTest.as_view()),
    path('redirect_test/', RedirectTest.as_view()),
    path('detail_test/<int:pk>', DetailViewTest.as_view()),
]
  1. templates\the_13文件夹创建 something_detail.html
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
    <h1>hello world</h1>
</body>
</html>
  1. 运行tutorial, 点击 http://127.0.0.1:8000/, 浏览器地址栏

ImproperlyConfigured at /the_13/detail_test/1 刷新

  1. 把 something_detail.html 移动到 templates\the_12文件夹,再刷新浏览器
  1. something_detail.html body 里面 添加 msg 是 {{ object.msg }}
复制代码
<body>
    <h1>hello world</h1>
    msg 是 {{ object.msg }}
</body>
  1. 刷新浏览器
  1. something_detail.html body 里面 去掉 msg 是
复制代码
<body>
    <h1>hello world</h1>
    {{ object.msg }}
</body>
  1. 刷新浏览器
  1. 把地址栏最后的数字,改成2,或者 3 刷新, 会得到第二条msg, 或者第三条msg

DetailView总结

  • 提供了什么功能: 提供了单个变量渲染到模板的功能
  • 数据从哪里来:

数据从什么地方获取到

复制代码
                model
                queryset
                get_queryset

怎么带着数据去查询的

复制代码
                get_object
                queryset = queryset.filter(pk=pk)
  • 提供了哪些模板变量

object

模型名小写(something) ??? 可以测试一下

context_object_name

  • 渲染的模板页

模型所在的子应用/模型名的小写_detail.html

template_name

本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
zybishe2 小时前
免费送源码:Java+ssm+MySQL 酒店预订管理系统的设计与实现 计算机毕业设计原创定制
java·大数据·python·mysql·微信小程序·php·课程设计
农民小飞侠3 小时前
ubuntu 安装pyllama教程
linux·python·ubuntu
草捏子3 小时前
主从延迟导致数据读不到?手把手教你架构级解决方案
后端
橘猫云计算机设计4 小时前
基于Python电影数据的实时分析可视化系统(源码+lw+部署文档+讲解),源码可白嫖!
数据库·后端·python·信息可视化·小程序·毕业设计
蹦蹦跳跳真可爱5894 小时前
Python----机器学习(基于贝叶斯的鸢尾花分类)
python·机器学习·分类
Yolo@~4 小时前
SpringBoot无法访问静态资源文件CSS、Js问题
java·spring boot·后端
Full Stack Developme4 小时前
SQL 全文检索原理
python·sql·全文检索
大鸡腿同学4 小时前
资源背后的成事密码
后端
爱的叹息4 小时前
JDK(Java Development Kit)从发布至今所有主要版本 的详细差异、新增特性及关键更新的总结,按时间顺序排列
java·数据库·python
qq3332129724(中职生)4 小时前
中职网络安全 MSF 漏洞 自动利用脚本 Python C模块
python·安全·web安全