django表单提交

前提:

使用django-admin startproject XXX创建了一个django项目【项目目录为project】

django-admin startproject project

一:控制器配置

在项目的根目录创建一个Controller目录,并在Controller目录下创建一个search.py

# -*- coding: utf-8 -*-
 
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.views.decorators import csrf
 
# 表单(用于渲染页面)
def index(request):
    return render_to_response('search/index.html')
 
# 接收GET请求数据
def get(request):
    request.encoding='utf-8'
    data = {}
    if ('keywords' in request.GET and request.GET['keywords']):
        data['keywords'] = '' + request.GET['keywords']
    else:
        data['keywords'] = '你提交了空表单'
    return render_to_response("search/index.html", data)

# @csrf.csrf_exempt  #当提交表单提示403时增加
def post(request):
    request.encoding='utf-8'
    data ={}

    if ('name' in request.POST and request.POST['name']):
        data['name'] = '' + request.POST['name']
    else:
        data['name'] = '你提交了空表单'
    return render_to_response("search/index.html", data)

二:视图渲染

在项目的根目录创建一个VIew目录,后续所有的视图文件都放在此目录下,并且需要修改配置文件project/settings.py文件中的视图目录地址

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR+"/View",],  #配置视图文件根目录
        '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',
            ],
        },
    },
]

根据上面的控制器我们在View目录下创建一个search目录并在search目录下创建一个index.html文件

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Examples</title>
</head>
<body>
    <form action="/search/get/" method="get">
        <input type="text" name="keywords">
        <input type="submit" value="GET搜索">
    </form>
    <p>GET搜索的内容为:{{ keywords }}</p>


     <form action="/search/post/" method="post">
        {% csrf_token %}
        <input type="text" name="name">
        <input type="submit" value="POST搜索">
    </form>
   	<p>POST搜索的内容为:{{ name }}</p>
</body>
</html>

在post提交表单的 html中增加一个{% csrf_token %},此标签专门用于防止伪装提交请求的功能

三:路由配置

修改路由配置文件project/urls.py文件中的路由配置

from django.contrib import admin
from django.urls import path
from Controller import search

urlpatterns = [
    path('search/', search.index),
    path('search/get/', search.get),
    path('search/post/', search.post),
]

运行服务

python manage.py runserver 0.0.0.0:8000

访问127.0.0.1:8000/search效果如下

四:Request 对象

Request 对象常用属性

|---------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 属性 | 描述 |
| path | 请求页面的全路径,不包括域名---例如, "/hello/"。 |
| method | 请求中使用的HTTP方法的字符串表示。全大写表示,如GET,POST |
| GET | 包含所有HTTP GET参数的类字典对象 |
| POST | 包含所有HTTP POST参数的类字典对象 |
| REQUEST | 为了方便,该属性是POST和GET属性的集合体,但是有特殊性,先查找POST属性,然后再查找GET属性。借鉴PHP中 $_REQUEST。 |
| COOKIES | 包含所有cookies的标准Python字典对象。Keys和values都是字符串。 |
| FILES | 包含所有上传文件的类字典对象。FILES中的每个Key都是<input type="file" name="" />标签中name属性的值. FILES中的每个value 同时也是一个标准Python字典对象,包含下面三个Keys: * filename: 上传文件名,用Python字符串表示 * content-type: 上传文件的Content type * content: 上传文件的原始内容 注意:只有在请求方法是POST,并且请求页面中<form>有enctype="multipart/form-data"属性时FILES才拥有数据。否则,FILES 是一个空字典。 |
| META | 包含所有可用HTTP头部信息的字典。 例如: * CONTENT_LENGTH * CONTENT_TYPE * QUERY_STRING: 未解析的原始查询字符串 * REMOTE_ADDR: 客户端IP地址 * REMOTE_HOST: 客户端主机名 * SERVER_NAME: 服务器主机名 * SERVER_PORT: 服务器端口 META 中这些头加上前缀HTTP_最为Key, 例如: * HTTP_ACCEPT_ENCODING * HTTP_ACCEPT_LANGUAGE * HTTP_HOST: 客户发送的HTTP主机头信息 * HTTP_REFERER: referring页 * HTTP_USER_AGENT: 客户端的user-agent字符串 * HTTP_X_BENDER: X-Bender头信息 |
| user | 是一个django.contrib.auth.models.User 对象,代表当前登录的用户。 如果访问用户当前没有登录,user将被初始化为django.contrib.auth.models.AnonymousUser的实例。 你可以通过user的is_authenticated()方法来辨别用户是否登录: if request.user.is_authenticated(): # 用于已登录 只有激活Django中的AuthenticationMiddleware时该属性才可用 |
| session | 唯一可读写的属性,代表当前会话的字典对象。只有激活Django中的session支持时该属性才可用。 |

相关推荐
Flying_Fish_roe2 分钟前
Spring Boot-RESTful API相关问题
spring boot·python·restful
芯冰乐14 分钟前
综合时如何计算net delay?
后端·fpga开发
叫我:松哥37 分钟前
基于机器学习的癌症数据分析与预测系统实现,有三种算法,bootstrap前端+flask
前端·python·随机森林·机器学习·数据分析·flask·bootstrap
我是瓦力38 分钟前
球形包围框-Bounding Sphere-原理-代码实现
人工智能·python·深度学习·计算机视觉·3d
拉玛干1 小时前
社团周报系统可行性研究-web后端框架对比-springboot,django,gin
数据库·python·spring·golang
Yan-英杰2 小时前
Encountered error while trying to install package.> lxml
开发语言·python·pandas·pip·issue
RS&2 小时前
python学习笔记
笔记·python·学习
AI原吾2 小时前
解锁自动化新境界:KeymouseGo,让键盘和鼠标动起来!
运维·python·自动化·计算机外设·keymousego
卡卡_R-Python2 小时前
海洋气象编程工具-Python
开发语言·python
北愚2 小时前
Scrapy爬虫实战——某瓣250
python·scrapy