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值

相关推荐
liann1196 分钟前
3.2_红队攻击框架--MITRE ATT&CK‌
python·网络协议·安全·网络安全·系统安全·信息与通信
云天AI实战派17 分钟前
AI 智能体问题排查指南:ChatGPT、API 调用到 Agent 上线失灵的全流程修复手册
大数据·人工智能·python·chatgpt·aigc
我的xiaodoujiao1 小时前
API 接口自动化测试详细图文教程学习系列15--项目实战演练2
python·学习·测试工具·pytest
多思考少编码2 小时前
PAT甲级真题1001 - 1005题详细题解(C++)(个人题解)
c++·python·最短路·pat·算法竞赛
ZhengEnCi2 小时前
M5-markconv自定义CSS样式指南 📝
前端·css·python
ZhengEnCi2 小时前
M4-更新日志v0.1.3-Mermaid图表支持 📝
python
hsjcjh3 小时前
多模态长文本协同:用Gemini 3.1 Pro镜像官网破解复杂办公场景的效率困局(国内实测方案)
python
凯瑟琳.奥古斯特3 小时前
SQLAlchemy核心功能解析
开发语言·python·flask
卷Java3 小时前
GPTQ vs AWQ vs GGUF:模型量化工具横向测评
开发语言·windows·python
ma_de_hao_mei_le3 小时前
ntquerysystemiunfomation 数据传递
django