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值

相关推荐
Hello.Reader26 分钟前
ClickHouse 与 Quickwit 集成实现高效查询
python·clickhouse·django·全文检索
技术无疆35 分钟前
【Python】Anaconda插件:Sublime Text中的Python开发利器
ide·python·编辑器·pip·pygame·sublime text·python3.11
加油=^_^=43 分钟前
MySQL基础篇的补充
数据库·python·mysql
鸽芷咕1 小时前
【Python报错已解决】ModuleNotFoundError: No module named ‘tensorflow‘
python·机器学习·tensorflow·bug·neo4j
李元豪1 小时前
python 自动化 win11 编程 实现 一键 启动多个软件,QQ浏览器,snipaste,pycharm软件
python·pycharm·自动化
痛&快乐着1 小时前
python-在PyCharm中使用PyQt5
python·qt·pycharm
fydw_7151 小时前
PyTorch 激活函数及非线性变换详解
人工智能·pytorch·python
Rverdoser1 小时前
在 PyCharm 中配置 Anaconda 环境
ide·python·pycharm
IT小辉同学2 小时前
用 Pygame 实现一个乒乓球游戏
python·游戏·pygame
虚假程序设计2 小时前
pythonnet python图像 C# .NET图像 互转
开发语言·人工智能·python·opencv·c#·.net