Django 10 表单

news2024/9/23 17:15:39

表单的使用流程

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.coloradmin.cn/o/1365201.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Kafka(五)生产者

目录 Kafka生产者1 配置生产者bootstrap.serverskey.serializervalue.serializerclient.id""acksallbuffer.memory33554432(32MB)compression.typenonebatch.size16384(16KB)max.in.flight.requests.per.connection5max.request.size1048576(1MB)receive.buffer.byte…

Fowsniff

靶场搭建 遇到扫描不到的情况&#xff0c;可以尝试改靶机的网络为NAT模式&#xff0c;在靶机启动时按”esc“&#xff0c;进入Advanced options for Ubantu&#xff0c;选择recovery mode&#xff0c;选择network&#xff0c;按方向键”→“&#xff0c;OK&#xff0c;然后res…

Python爬虫获取百度的图片

一. 爬虫的方式&#xff1a; 主要有2种方式: ①ScrapyXpath (API 静态 爬取-直接post get) ②seleniumXpath (点击 动态 爬取-模拟) ScrapyXpath XPath 是 Scrapy 中常用的一种解析器&#xff0c;可以帮助爬虫定位和提取 HTML 或 XML 文档中的数据。 Scrapy 中使用 …

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

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

【代码】Keras3.0:实现残差连接

简介 残差连接是一种非常重要的网络结构创新&#xff0c;最早被广泛应用于ResNet&#xff08;Residual Neural Network&#xff09;模型中&#xff0c;由何凯明等人在2015年的论文"Deep Residual Learning for Image Recognition"中提出。 核心思想 通过引入“short…

【Sharding-Sphere 整合SpringBoot】

Sharding-Jdbc在3.0后改名为Sharding-Sphere。Sharding-Sphere相关资料&#xff0c;请自行网上查阅&#xff0c;这里仅仅介绍了实战相关内容&#xff0c;算是抛砖引玉。 Sharding-Sphere 整合SpringBoot 一、项目准备二、项目实战1. pom.xml及application.yml2. OrderInfoCont…

大数据 Yarn - 资源调度框架

Hadoop主要是由三部分组成&#xff0c;除了前面我讲过的分布式文件系统HDFS、分布式计算框架MapReduce&#xff0c;还有一个是分布式集群资源调度框架Yarn。 但是Yarn并不是随Hadoop的推出一开始就有的&#xff0c;Yarn作为分布式集群的资源调度框架&#xff0c;它的出现伴随着…

Mac M1 Parallels CentOS7.9 Deploy Docker + Rancher + K8S(HA+More Master)

一、准备虚拟机资源 虚拟机清单 机器名称IP地址角色rancher10.211.55.200管理K8S集群k8svip10.211.55.199K8S VIPmaster0110.211.55.201K8S集群主节点master0210.211.55.202K8S集群主节点master0310.211.55.203K8S集群主节点node0110.211.55.211K8S集群从节点node0210.211.55…

nvm安装教程,实现node的多版本管理(图文界面)

目录 前言1. 安装配置2. 使用方式 前言 由于前端项目不同的node版本&#xff0c;导致重复的卸载安装会比较麻烦&#xff0c;对此需要nvm来管理 类似python版本的差异&#xff0c;可以使用虚拟环境管理&#xff08;anconda&#xff09;&#xff0c;在我原先的文章也有讲解过 …

Hive精选10道面试题

1.Hive内部表和外部表的区别&#xff1f; 内部表的数据由Hive管理&#xff0c;外部表的数据不由Hive管理。 在Hive中删除内部表后&#xff0c;不仅会删除元数据还会删除存储数据&#xff0c; 在Hive中删除外部表后&#xff0c;只会删除元数据但不会删除存储数据。 内部表一旦…

Basal前端梳理

Basalt前端逻辑梳理 TBB安装参考 https://zhuanlan.zhihu.com/p/480823197 代码注释参考 https://blog.csdn.net/qq_39266065/article/details/106175701#t7 光流追踪参考 https://blog.csdn.net/weixin_41738773/article/details/130282527 VI Odometry KLT tracking 原理 …

new和delete表达式的工作步骤

new表达式工作步骤 调用一个operator new库函数开辟未类型化的空间 void *operator new(size_t); 在为类型化的空间上调用构造函数&#xff0c;初始化对象的成员 返回相应类型的指针 delete表达式工作步骤 调用相应类型的析构函数,但析构函数并不能删除对象所在的空间&…

【linux学习笔记】网络

目录 【linux学习笔记】网络检查、监测网络ping-向网络主机发送特殊数据包traceroute-跟踪网络数据包的传输路径netstat-检查网络设置及相关统计数据 【linux学习笔记】网络 检查、监测网络 ping-向网络主机发送特殊数据包 最基本的网络连接命令就是ping命令。ping命令会向指…

062:vue中将一维数组变换为三维数组(图文示例)

第062个 查看专栏目录: VUE ------ element UI 专栏目标 在vue和element UI联合技术栈的操控下&#xff0c;本专栏提供行之有效的源代码示例和信息点介绍&#xff0c;做到灵活运用。 &#xff08;1&#xff09;提供vue2的一些基本操作&#xff1a;安装、引用&#xff0c;模板使…

Leetcode2487. 从链表中移除节点

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

计算机基础面试题 |16.精选计算机基础面试题

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

how2heap-2.23-11-poison_null_byte

什么是poison_null_byte 当然不止这一种&#xff0c;下面最简单的形式 #include <malloc.h> int main() {char * a malloc(0x200);char * b malloc(0x200);size_t real_size malloc_usable_size(a);a[real_size] 0;return 0; }影响&#xff1a; chunk a&#xff0…

【Hadoop】说下HDFS读文件和写文件的底层原理?

文件读取文件的写入 文件读取 客户端调用 FileSystem 对象的 open&#xff08;&#xff09;函数&#xff0c;打开想要读取的文件。其中FileSystem 是 DistributeFileSystem 的一个实例&#xff1b;DistributedFileSystem 通过使用 RPC&#xff08;远程过程调用&#xff09; 访N…

Large Language Models Paper 分享

论文1&#xff1a; ChatGPTs One-year Anniversary: Are Open-Source Large Language Models Catching up? 简介 2022年11月&#xff0c;OpenAI发布了ChatGPT&#xff0c;这一事件在AI社区甚至全世界引起了轰动。首次&#xff0c;一个基于应用的AI聊天机器人能够提供有帮助、…

vue3组件传参

1、props: 2、自定义事件子传父 3、mitt任意组件通讯 4、v-model通讯(v-model绑定在组件上) (1)V2中父子组件的v-model通信&#xff0c;限制了popos接收的属性名必须为value和emit触发的事件名必须为input,所以有时会有冲突; 父组件: 子组件: (2)V3中:限制了popos接收的属性名…