Django 10 表单

表单的使用流程

1. 定义

1. terminal 输入 django-admin startapp the_14回车

2. tutorial子文件夹 settings.py  INSTALLED_APPS 中括号添加  "the_14",

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "the_3",
    "the_5",
    "the_6",
    "the_7",
    "the_8",
    "the_9",
    "the_10",
    "the_12",
    "the_13",
    "the_14",
]

3. tutorial子文件夹 urls.py 

from django.contrib import admin
from django.urls import path,include
import the_3.urls

urlpatterns = [
    path('admin/', admin.site.urls),
    path('the_3/', include('the_3.urls')),
    path('the_4/', include('the_4.urls')),
    path('the_5/', include('the_5.urls')),
    path('the_7/', include('the_7.urls')),
    path('the_10/', include('the_10.urls')),
    path('the_12/', include('the_12.urls')),
    path('the_13/', include('the_13.urls')),
    path('the_14/', include('the_14.urls')),
]

4. the_14 子文件夹添加 urls.py 

from django.urls import path
from .views import hello

urlpatterns = [
    path('hello/', hello),
]

5. the_14\views.py 

from django.http import HttpResponse
from django.shortcuts import render


# Create your views here.

def hello(request):
    return HttpResponse('hello world')

6. 运行tutorial, 点击 http://127.0.0.1:8000/, 浏览器地址栏 127.0.0.1:8000/the_14/hello/  刷新 

7. 定义表单, 在 the_14文件夹创建 forms.py文件 

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='你的名字', max_length=10)

8. the_14\views.py 

from django.http import HttpResponse
from django.shortcuts import render


# Create your views here.

def hello(request):
    return render(request, 'the_14/hello.html')

9. templates创建the_14子文件夹,再在 the_14子文件夹创建 hello.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>我是表单页面</h1>
</body>
</html>

10.  运行tutorial, 点击 http://127.0.0.1:8000/, 浏览器地址栏 127.0.0.1:8000/the_14/hello/  刷新 

11. 我想把form的内容渲染到前端去,首先the_14\views.py 写入

from django.http import HttpResponse
from django.shortcuts import render
from .forms import NameForm


# Create your views here.

def hello(request):
    form = NameForm()
    return render(request, 'the_14/hello.html', {'myform':form})

其次,在 template\the_14\hello.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>我是表单页面</h1>
    {{ myform }}
</body>
</html>

刷新网页

注意: 这里是没办法提交的,如果想提交, 需要嵌套一个form表单 

<body>
    <h1>我是表单页面</h1>
    <form action="">
    {{ myform }}
    </form>
</body>

表单的绑定与非绑定 

绑定就是说表单里面有值了,非绑定就是表单里面还没有值

表单提交了就是有值, 没有提交或者提交错误就是拿不到值, 拿不到值就是非绑定的状态。

怎么证明表单里面没有值

the_14\views.py 

from django.http import HttpResponse
from django.shortcuts import render
from .forms import NameForm


# Create your views here.

def hello(request):
    form = NameForm()
    import pdb
    pdb.set_trace()
    return render(request, 'the_14/hello.html', {'myform':form})

重新运行,刷新网页, terminal 输入 p form 回车

-> return render(request, 'the_14/hello.html', {'myform':form})
(Pdb) p form 
<NameForm bound=False, valid=Unknown, fields=(your_name)> 

bound=False 就是非绑定的状态 

terminal 再输入 p dir(form) 回车 

(Pdb) p dir(form)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__html__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_bound_fields_cache', '_clean_fields', '_clean_form', '_errors', '_html_output', '_post_clean', 'add_error', 'add_initial_prefix', 'add_prefix', 'as_p', 'as_table', 'as_ul', 'auto_id', 'base_fields', 'changed_data', 'clean', 'data', 'declared_fields', 'default_renderer', 'empty_permitted', 'error_class', 'errors', 'field_order', 'fields', 'files', 'full_clean', 'get_initial_for_field', 'has_changed', 'has_error', 'hidden_fields', 'initial', 'is_bound', 'is_multipart', 'is_valid', 'label_suffix', 'media', 'non_field_errors', 'order_fields', 'prefix', 'renderer', 'use_required_attribute', 'visible_fields']

is_bound 判断是否绑定的状态 

terminal 输入 p form.is_bound回车 , False指的是非绑定状态

(Pdb) p form.is_bound
False

terminal 输入 c回车, 结束调试

(Pdb) c
[07/Jan/2024 19:10:13] "GET /the_14/hello/ HTTP/1.1" 200 344

2.渲染

渲染表单到模板 

{{ form.as_table }}、{{ form.as_table }}、{{ form.as_p }}、{{ form.as_ul }}
{{ form.attr }}

the_14\hello.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>我是表单页面</h1>
    <form action="" method="post">
    账号:{{ myform.your_name }}
        <input type="submit" value="上传">
    </form>
</body>
</html>

表单验证

  • 字段验证
  • 基于cleaned_data的类方法: clean_<fieldname>()
  • 基于cleaned_data的类方法:clean()

表单使用:其实是包含的两个请求的

第一个请求, get请求,这个请求可以拿到网页,展示页面

第二个请求, post请求,这个请求主要是提供数据给后台 , 注意:需要声明请求的url

templates\the_14\hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>我是表单页面</h1>
    <form action="{% url 'form_hello' %}" method="post">
    账号:{{ myform.your_name }}
        <input type="submit" value="上传">
    </form>
</body>
</html>

the_14\urls.py

from django.urls import path
from .views import hello

urlpatterns = [
    path('hello/', hello, name='form_hello'),
]

the_14\views.py 

from django.http import HttpResponse
from django.shortcuts import render
from .forms import NameForm


# Create your views here.

def hello(request):
    form = NameForm()
    # import pdb
    # pdb.set_trace()
    print(form.is_bound)
    return render(request, 'the_14/hello.html', {'myform':form})

刷新网页,输入名字panda, 点击上传,可以看到有两个False, 执行了两次。

False
[07/Jan/2024 20:56:07] "GET /the_14/hello/ HTTP/1.1" 200 352
False
[07/Jan/2024 20:56:13] "POST /the_14/hello/ HTTP/1.1" 200 352

第二次优化

the_14\views.py 

from Scripts.bottle import view
from django.http import HttpResponse
from django.shortcuts import render
from .forms import NameForm


# Create your views here.

# def hello(request):
#     request.method = 'GET'
#     form = NameForm()
#     # import pdb
#     # pdb.set_trace()
#     print(form.is_bound)
#     return render(request, 'the_14/hello.html', {'myform':form})

class Hello(view):
    def get(self, request):
        form = NameForm()
        return render(request, 'the_14/hello.html', {'myform': form})

    def post(self,request):
        form = NameForm(request.POST)
        return render(request, 'the_14/hello.html', {'myform': form,'post':True})

the_14\urls.py

from django.urls import path
from .views import Hello

urlpatterns = [
    # path('hello/', hello, name='form_hello'),
    path('hello/', Hello.as_view(), name='form_hello'),
]

刷新网页,输入 panda提交, 浏览器页面会出来 这里是post返回的内容。

字段验证

输入的字段受 max_length的长度限制

基于cleaned_data的类方法: clean_<fieldname>()

def post(self,request): form = NameForm(request.POST) # form.data # 属于原始数据 if form.is_valid(): # 是否校验过 print(form.cleaned_data) # 校验之后的数据, 干净的数据 return render(request, 'the_14/hello.html', {'myform': form,'post':True})

the_14\forms.py 

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='你的名字', max_length=10)

    def clean_your_name(self):  # 专门校验your_name
        your_name = self.cleaned_data['your_name']
        if your_name.startswith('fuck'):
            raise forms.ValidationError('不能带脏字哟!')  # 不通过就主动抛出错误
        return your_name

the_14\views.py 

from Scripts.bottle import view
from django.http import HttpResponse
from django.shortcuts import render
from .forms import NameForm


# Create your views here.

# def hello(request):
#     request.method = 'GET'
#     form = NameForm()
#     # import pdb
#     # pdb.set_trace()
#     print(form.is_bound)
#     return render(request, 'the_14/hello.html', {'myform':form})

class Hello(view):
    def get(self, request):
        form = NameForm()
        return render(request, 'the_14/hello.html', {'myform': form})

    def post(self,request):
        form = NameForm(request.POST)
        # form.data # 属于原始数据
        if form.is_valid(): # 是否校验过
            print(form.cleaned_data) # 校验之后的数据, 干净的数据
        else:
            print(form.errors)
        return render(request, 'the_14/hello.html', {'myform': form,'post':True})

刷新浏览器, 输入 fuck_panda, 上传就会出现以下内容

基于cleaned_data的类方法:clean()

如果有多个字段,应该怎么校验

the_14 \forms.py 添加 your_title = forms.CharField(label='你的头衔', max_length=10)

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='你的名字', max_length=10)
    your_title = forms.CharField(label='你的头衔', max_length=10)

    def clean_your_name(self):  # 专门校验your_name
        your_name = self.cleaned_data['your_name']
        if your_name.startswith('fuck'):
            raise forms.ValidationError('不能带脏字哟!')  # 不通过就主动抛出错误
        return your_name

templates\the_14\hello.html
 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>我是表单页面</h1>
    <form action="{% url 'form_hello' %}" method="post">
        账号:{{ myform.your_name }} <br>
        头衔:{{ myform.your_title }} <br>
        <input type="submit" value="上传">
    </form>
    {% if post %}
        <div>这里是post返回的内容</div>
    {% endif %}
</body>
</html>

刷新网页 

templates\the_14\hello.html 也可以只写 {{ myform }}

    <form action="{% url 'form_hello' %}" method="post">
{#        账号:{{ myform.your_name }} <br>#}
{#        头衔:{{ myform.your_title }} <br>#}
        {{ myform }}
        <input type="submit" value="上传">
    </form>

刷新网页 

the_14\forms.py 

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='你的名字', max_length=10)
    your_title = forms.CharField(label='你的头衔', max_length=10)

    def clean_your_name(self):  # 专门校验your_name
        your_name = self.cleaned_data.get('your_name', '')
        if your_name.startswith('fuck'):
            raise forms.ValidationError('不能带脏字哟!')  # 不通过就主动抛出错误
        return your_name

    """
    如果名字以pd开头,头衔必须使用金牌     
    """

    def clean(self):
        name = self.cleaned_data.get('your_name','')
        title = self.cleaned_data.get('your_title', '')

        if name.startswith('pd_') and title != "金牌":
            raise forms.ValidationError('如果名字以pd开头,头衔必须使用金牌')

刷新网页,输入 fuck_panda , pfshjln 上传 

如果使用['your_name']自定义的验证之后,还会进行clean()的联合校验,但是自定义没有通过,数据是不会填充到clean里面来的,所以
self.cleaned_data['your_name'] 是取不到值的
属性验证

the_14\forms.py

from django import forms
from django.core.validators import MinLengthValidator


class NameForm(forms.Form):
    your_name = forms.CharField(label='你的名字', max_length=10,validators=[MinLengthValidator(3,'你的长度应该要大于3个')])

    your_title = forms.CharField(label='你的头衔', max_length=10)

刷新网页,填入 1, unknown, 点击上传, 浏览器返回 

自定义验证器 - (from django.core import validators)

the_14\forms.py 

from django import forms
from django.core.validators import MinLengthValidator

def my_validator(value):
    if len(value) < 4:
        raise forms.ValidationError('你写少了,赶紧修改')

class NameForm(forms.Form):
    # your_name = forms.CharField(label='你的名字', max_length=10,validators=[MinLengthValidator(3,'你的长度应该要大于3个')])
    your_name = forms.CharField(label='你的名字', max_length=10, validators=[my_validator])
    your_title = forms.CharField(label='你的头衔', max_length=10)

刷新网页,输入 111, unknown 点击上传 

3. 提交

4. 校验

5. 保存

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/300960.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

关于burpsuite设置HTTP或者SOCKS代理

使用burpsuite给自己的浏览器做代理&#xff0c;抓包重发这些想必大家都清除 流量请求过程&#xff1a; 本机浏览器 -> burpsuite -> 目标服务器 实质还是本机发出的流量 如果我们想让流量由其他代理服务器发出 实现&#xff1a; 本机浏览器 -> burpsuite -> 某…

离散数学1

注&#xff1a;线性代数已经更新了最大部分的内容&#xff0c;因此过段时间再补充剩余内容。 小王能歌善舞。因此&#xff0c;小王必须得会唱歌也必须得会跳舞&#xff0c;才满足题意 小王能唱歌或者小王能跳舞。因此&#xff0c;小王会唱歌也会跳舞满足。小王不会唱歌但会跳舞…

【ros笔记】urdf文件

urdf文件属于xml文件&#xff0c;他的标签有&#xff1a; <robot name"robot_name"><!-- 看的见摸的着刚体用link --><link name"base_link"><!-- 可视化部分 --><visual><!-- 几何形状 --><geometry><!-- b…

CNN——ResNet

深度残差网络&#xff08;Deep residual network, ResNet&#xff09;的提出是CNN图像史上的一件里程碑事件&#xff0c;并且让深度学习真正可以继续做下去&#xff0c;斩获2016 CVPR Best Paper。此外ResNet的作者都是中国人&#xff0c;一作何恺明。ResNet被提出以后很多的网…

e2studio开发LPS28DFW气压计(1)----轮询获取气压计数据

e2studio开发LPS28DFW气压计.1--轮询获取气压计数据 概述视频教学样品申请完整代码下载产品特性通信模式速率新建工程工程模板保存工程路径芯片配置工程模板选择时钟设置UART配置UART属性配置设置e2studio堆栈e2studio的重定向printf设置R_SCI_UART_Open()函数原型回调函数user…

单调栈与单调队列

目录 单调栈 单调队列 单调栈 题目如下&#xff1a; 如何维护一个单调栈&#xff1f; 单调递增栈&#xff1a;在保持栈内元素单调递增的前提下&#xff08;如果栈顶元素大于要入栈的元素&#xff0c;将将其弹出&#xff09;&#xff0c;将新元素入栈。单调递减栈&#xff1…

Leetcode2487. 从链表中移除节点

Every day a Leetcode 题目来源&#xff1a;2487. 从链表中移除节点 解法1&#xff1a;单调栈 遍历链表&#xff0c;建立一个单调栈&#xff08;单调递减&#xff09;。 再用头插法将单调栈的元素建立一个新的链表&#xff0c;返回该链表的头结点。 代码&#xff1a; /*…

湖南大学-计算机网路-2023期末考试【部分原题回忆】

前言 计算机网络第一门考&#xff0c;而且没考好&#xff0c;回忆起来的原题不多。 这门学科学的最认真&#xff0c;复习的最久&#xff0c;考的最差。 教材使用这本书&#xff1a; 简答题&#xff08;6*530分&#xff09; MTU和MSS分别是什么&#xff0c;联系是什么&#x…

深入了解static关键字的作用和应用--java面向对象学习

Static修饰成员变量 Static是什么 叫静态&#xff0c;可以修饰成员变量&#xff0c;成员方法 成员变量按有无static修饰分俩种&#xff1a; 类变量&#xff1a;有static修饰&#xff0c;属于类&#xff0c;在计算机里只有一份&#xff0c;会被类的全部对…

VMware NAT 模式,网关无法ping通 网关解决办法

开启红框服务即可。。 参考&#xff1a;VMware NAT 模式&#xff0c;网关无法ping通 网关解决办法_vmware设置net,本机ping不通网关-CSDN博客

StarRocks 在小红书自助分析场景的应用与实践

作者&#xff1a;小红书 OLAP 研发负责人 王成 近两年 StarRocks 一直是小红书 OLAP 引擎体系里非常重要的部分&#xff0c;过去一年&#xff0c;小红书的 StarRocks 使用规模呈现出翻倍的增长速度&#xff0c;目前整体规模已经达到 30 个集群&#xff0c;CPU 规模已经达到了 3…

传感数据分析——高通滤波与低通滤波

传感数据分析——高通滤波与低通滤波 文章目录 传感数据分析——高通滤波与低通滤波前言一、运行环境二、Python实现总结 前言 对于传感信号而言&#xff0c;我们可以提取其中的高频信息和低频信息&#xff0c;低频信息往往是信号的趋势&#xff0c;高频信息往往是一些突变或异…

vue3+echarts应用——深度遍历html的dom结构并用树图进行可视化

文章目录 ⭐前言&#x1f496;vue3系列文章 ⭐html数据解析&#x1f496; html字符串转为html对象&#x1f496; 深度遍历html对象内容 ⭐echarts 树图的渲染&#x1f496; 处理html内容为树状结构&#x1f496; 渲染树状图&#x1f496; inscode代码块 ⭐总结⭐结束 ⭐前言 大…

(低级错误)IDEA/Goland报错连接数据库失败:URL错误和权限问题。

前言 做毕设ing&#xff0c;使用Goland自带的数据库工具连接服务器的数据库。报错 错误: Malformed database URL, failed to parse the main URL sections. (view)服务器是华为云&#xff0c;使用宝塔面板。数据库版本5.6.50。 排查过程 鉴于Goland报错报的狗屁不是&#…

hfish蜜罐docker部署

centos 安装 docker-CSDN博客Docker下载部署 Docker是我们推荐的部署方式之一&#xff0c;当前的版本拥有以下特性&#xff1a; 自动升级&#xff1a;每小时请求最新镜像进行升级&#xff0c;升级不会丢失数据。数据持久化&#xff1a;在宿主机/usr/share/hfish目录下建立dat…

[足式机器人]Part3 机构运动学与动力学分析与建模 Ch00-1 坐标系与概念基准

本文仅供学习使用&#xff0c;总结很多本现有讲述运动学或动力学书籍后的总结&#xff0c;从矢量的角度进行分析&#xff0c;方法比较传统&#xff0c;但更易理解&#xff0c;并且现有的看似抽象方法&#xff0c;两者本质上并无不同。 2024年底本人学位论文发表后方可摘抄 若有…

编码风格之(3)GUN软件标准风格(1)

GNU软件编码标准风格(1) Author&#xff1a;Onceday Date: 2023年12月26日 漫漫长路&#xff0c;才刚刚开始… 本文主要翻译自《GNU编码标准》(GNU Coding Standards)一文。 参考文档: Linux kernel coding style — The Linux Kernel documentationGNU Coding Standards …

prometheus 黑盒监控

黑盒监控 “白盒监控” 是需要把对应的Exporter程序安装到被监控的目标主机上&#xff0c;从而实现对主机各种资源以及状态的数据采集工作 ”黑盒监控“ 是不需要把Exporter程序部署到被监控的目标主机上&#xff0c;比如全球的网络质量的稳定性&#xff0c;通常用ping操作&am…

【网络技术】【Kali Linux】Wireshark嗅探(八)动态主机配置协议(DHCP)

一、实验目的 本次实验使用 Wireshark &#xff08;“网鲨”&#xff09;流量分析工具进行网络流量嗅探&#xff0c;旨在初步了解动态主机配置协议&#xff08;DHCP协议&#xff09;的工作原理。 二、DHCP协议概述 动态主机配置协议&#xff08; D ynamic H ost C onfigurat…

Transformer - Attention is all you need 论文阅读

虽然是跑路来NLP&#xff0c;但是还是立flag说要做个project&#xff0c;结果kaggle上的入门project给的例子用的是BERT&#xff0c;还提到这一方法属于transformer&#xff0c;所以大概率读完这一篇之后&#xff0c;会再看BERT的论文这个样子。 在李宏毅的NLP课程中多次提到了…
最新文章