Django 视图类

在Django框架中,视图类(Class-based views,简称CBVs)提供了一个面向对象的方式来定义视图。这种方式可以让你通过创建类来组织视图逻辑,而不是使用基于函数的视图(Function-based views,简称FBVs)。CBVs带来了可重用性和模块化等优势,尤其是在处理标准的CRUD操作时。

1,创建应用

复制代码
 python manage.py startapp app2

2,创建模版文件

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form method="POST">
{% csrf_token %}
  <p>用户名</p>
  <input type="text" name="username">
  <input type="submit" value="提交">
</form>

</body>
</html>

3,配置模版路径

Test/Test/settings.py

复制代码
import os

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

4,注册应用

Test/Test/settings.py

5,添加视图函数

Test/app2/views.py

复制代码
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.views import View

class MyView(View):
    def get(self, request):
        # 处理GET请求的逻辑
        return HttpResponse('get, Hello, World!')

    def post(self, request):
        # 处理POST请求的逻辑
        print(request.method)
        print(request.POST.get('username'))
        return HttpResponse('post, Hello, World!')

6,添加路由地址

复制代码
from django.urls import path
from app2.views import MyView

urlpatterns = [
    path('MyView', MyView.as_view(), name='MyView'),
]

7,测试接口

Test/Test/settings.py

ps:这个中间件是为了防止跨站请求伪造的,平时用网页表单请求时,post提交是没有问题的,但是用api调用时就会被禁止,为了能使用接口调用post请求,需要注释掉。

复制代码
import requests

res_get = requests.get(url='http://127.0.0.1:8000/app2/MyView')
print(res_get.text)


res_post = requests.post(url='http://127.0.0.1:8000/app2/MyView' , data={'username':'admin'})
print(res_post.text)

分别成功请求get,post接口,获取接口请求的admin值

相关推荐
Dingdangcat862 分钟前
视杯视盘分割与青光眼检测_faster-rcnn_hrnetv2p-w32-1x_coco模型应用实践
python
喵手3 分钟前
Python爬虫实战:携程景点数据采集实战:从多页列表到结构化数据集(附SQLite持久化存储)!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·携程景点数据采集·sqlite存储采集数据
无垠的广袤3 分钟前
【VisionFive 2 Lite 单板计算机】边缘AI视觉应用部署:人脸检测
linux·人工智能·python·opencv·开发板
yuankoudaodaokou3 分钟前
突破大型工件测量瓶颈:思看科技在风电与船舶制造中的革新应用
python·科技·制造
Allen_LVyingbo10 分钟前
面向70B多模态医疗大模型预训练的工程落地(医疗大模型预训练扩展包)
人工智能·python·分类·知识图谱·健康医疗·迁移学习
Deng87234734811 分钟前
电脑使用 Gemini出了点问题解决办法
人工智能·python
我送炭你添花15 分钟前
Pelco KBD300A 模拟器:18. 按依赖顺序 + 复杂度由低到高逐步推进pytest单元测试
python·单元测试·log4j·pytest
程序员杰哥18 分钟前
如何写出高效的测试用例?
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
2301_8223776518 分钟前
数据分析师的Python工具箱
jvm·数据库·python
无垠的广袤27 分钟前
【VisionFive 2 Lite 单板计算机】SoC 温度的 Home Assistant 物联网终端显示
linux·python·物联网