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值

相关推荐
m0_624578591 小时前
MySQL主从复制支持跨版本吗_不同版本间同步的注意事项
jvm·数据库·python
yuanpan1 小时前
Python Pygame 入门教程:从零学会创建窗口、绘图和游戏交互
python·游戏·pygame
2401_871492852 小时前
如何在 React Router v6 中正确配置多路由组件显示
jvm·数据库·python
神仙别闹3 小时前
基于Python(Django)+MySQL 实现(Web)SQL智能检测系统的设计与实现
python·mysql·django
甄心爱学习3 小时前
【项目实训】法律文书智能摘要系统4
python·github·个人开发
huzhongqiang3 小时前
Playwright理解与封装
python
zhangchaoxies3 小时前
MySQL触发器能否监控特定用户操作_结合审计功能实现分析
jvm·数据库·python
qq_413502023 小时前
如何解决ORA-12518监听程序无法分配进程_内存耗尽与PGA溢出
jvm·数据库·python
zhangrelay3 小时前
三分钟云课实践速通--大学物理--python 版
linux·开发语言·python·学习·ubuntu·lubuntu
djjdjdjdjjdj4 小时前
如何用参数解构在函数入口处直接提取对象属性
jvm·数据库·python