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

相关推荐
骆晨学长6 分钟前
基于springboot的智慧社区微信小程序
java·数据库·spring boot·后端·微信小程序·小程序
AskHarries11 分钟前
利用反射实现动态代理
java·后端·reflect
Flying_Fish_roe35 分钟前
Spring Boot-Session管理问题
java·spring boot·后端
农民小飞侠1 小时前
python AutoGen接入开源模型xLAM-7b-fc-r,测试function calling的功能
开发语言·python
战神刘玉栋1 小时前
《程序猿之设计模式实战 · 观察者模式》
python·观察者模式·设计模式
敲代码不忘补水1 小时前
Python 项目实践:简单的计算器
开发语言·python·json·项目实践
hai405871 小时前
Spring Boot中的响应与分层解耦架构
spring boot·后端·架构
鸽芷咕2 小时前
【Python报错已解决】ModuleNotFoundError: No module named ‘paddle‘
开发语言·python·机器学习·bug·paddle
子午2 小时前
动物识别系统Python+卷积神经网络算法+TensorFlow+人工智能+图像识别+计算机毕业设计项目
人工智能·python·cnn
风等雨归期3 小时前
【python】【绘制小程序】动态爱心绘制
开发语言·python·小程序