網(wǎng)站首頁 編程語言 正文
主題
眾所周知,django.forms
極其強(qiáng)大,不少的框架也借鑒了這個(gè)模式,如Scrapy
。在表單驗(yàn)證時(shí),django.forms
是一絕,也是面向?qū)ο蟮慕?jīng)典表現(xiàn)。但要用它來渲染表單那就不好玩了,除非寫框架。本文章主要縷一縷如何使用django.forms來做表單驗(yàn)證。
django項(xiàng)目基本信息
- models.py
from django.db import models class Article(models.Model): title = models.CharField(max_length=50, verbose_name='標(biāo)題') content = models.TextField(verbose_name='內(nèi)容') create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title
- forms.py
同目錄下創(chuàng)建一個(gè)forms.py
from django.forms import ModelForm from django import forms from . models import Article from django.core.exceptions import ValidationError class ArticleForm(ModelForm): class Meta: model = Article exclude = ['id'] def clean(self): cleaned_data = super().clean() title = cleaned_data.get('title') if 'My' not in title: raise ValidationError('標(biāo)題中必須包含My字樣', code='title')
- views.py
在views中,創(chuàng)建一個(gè)增加Article的方法
def add(request): if request.method == 'GET': return render(request, 'add.html') else: form = ArticleForm(request.POST) # 主要了解的是表單的驗(yàn)證 if form.is_valid(): form.save() return HttpResponseRedirect('/show/') else: form.errors.as_data() # {'__all__': [ValidationError(['標(biāo)題中必須包含My字樣'])]} form.errors.get_context() # {'errors': dict_items([('__all__', ['標(biāo)題中必須包含My字樣'])]), 'error_class': 'errorlist'} d = form.errors.get_json_data() # {'__all__': [{'message': '標(biāo)題中必須包含My字樣', 'code': 'title'}]} return HttpResponse(d.get('__all__'))
核心分析
如果是在admin中使用ModelForm的驗(yàn)證,那也是非常方便的,如果我們要在用戶的前端響應(yīng)中使用表單驗(yàn)證,且又不通過django.forms渲染的表單來傳遞驗(yàn)證結(jié)果,則需要看看源碼:ModelForm.errors
。errors
是ErrorDict()
的實(shí)例,ErrorDict
源碼:
class ErrorDict(dict, RenderableErrorMixin): """ A collection of errors that knows how to display itself in various formats. The dictionary keys are the field names, and the values are the errors. """ template_name = "django/forms/errors/dict/default.html" template_name_text = "django/forms/errors/dict/text.txt" template_name_ul = "django/forms/errors/dict/ul.html" def __init__(self, *args, renderer=None, **kwargs): super().__init__(*args, **kwargs) self.renderer = renderer or get_default_renderer() def as_data(self): return {f: e.as_data() for f, e in self.items()} def get_json_data(self, escape_html=False): return {f: e.get_json_data(escape_html) for f, e in self.items()} def get_context(self): return { "errors": self.items(), "error_class": "errorlist", }
三個(gè)方法返回的都是字典,但數(shù)據(jù)結(jié)構(gòu)不同,可以看情況而定。值得注意的是,在ArticleForm
中,raise ValidationError時(shí),如果code傳入?yún)?shù)時(shí),它將會(huì)在get_context()
中顯式體現(xiàn)出來。
總結(jié)
1、掌握這個(gè)原理,傳統(tǒng)的全棧開發(fā)可以節(jié)省更多的時(shí)間。
2、多看源碼
原文鏈接:https://www.cnblogs.com/mooremok/p/17003453.html
相關(guān)推薦
- 2022-04-21 R語言繪制帶ErrorBar的分組條形圖代碼的分享_R語言
- 2022-12-04 深入了解Rust的切片使用_Rust語言
- 2023-01-20 python如何實(shí)現(xiàn)完全數(shù)_python
- 2023-10-17 uniapp通過功能性編碼跳轉(zhuǎn)到原生的app頁面
- 2022-05-03 Shell內(nèi)置命令教程之a(chǎn)lias和echo_linux shell
- 2022-03-09 C++使用map實(shí)現(xiàn)多進(jìn)程拷貝文件的程序思路_C 語言
- 2022-11-23 shell?循環(huán)命令詳解_linux shell
- 2024-01-14 npm install時(shí) cannot read properties of null的問題
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支