網站首頁 編程語言 正文
主題
眾所周知,django.forms
極其強大,不少的框架也借鑒了這個模式,如Scrapy
。在表單驗證時,django.forms
是一絕,也是面向對象的經典表現。但要用它來渲染表單那就不好玩了,除非寫框架。本文章主要縷一縷如何使用django.forms來做表單驗證。
django項目基本信息
- models.py
from django.db import models class Article(models.Model): title = models.CharField(max_length=50, verbose_name='標題') content = models.TextField(verbose_name='內容') create_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title
- forms.py
同目錄下創建一個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('標題中必須包含My字樣', code='title')
- views.py
在views中,創建一個增加Article的方法
def add(request): if request.method == 'GET': return render(request, 'add.html') else: form = ArticleForm(request.POST) # 主要了解的是表單的驗證 if form.is_valid(): form.save() return HttpResponseRedirect('/show/') else: form.errors.as_data() # {'__all__': [ValidationError(['標題中必須包含My字樣'])]} form.errors.get_context() # {'errors': dict_items([('__all__', ['標題中必須包含My字樣'])]), 'error_class': 'errorlist'} d = form.errors.get_json_data() # {'__all__': [{'message': '標題中必須包含My字樣', 'code': 'title'}]} return HttpResponse(d.get('__all__'))
核心分析
如果是在admin中使用ModelForm的驗證,那也是非常方便的,如果我們要在用戶的前端響應中使用表單驗證,且又不通過django.forms渲染的表單來傳遞驗證結果,則需要看看源碼:ModelForm.errors
。errors
是ErrorDict()
的實例,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", }
三個方法返回的都是字典,但數據結構不同,可以看情況而定。值得注意的是,在ArticleForm
中,raise ValidationError時,如果code傳入參數時,它將會在get_context()
中顯式體現出來。
總結
1、掌握這個原理,傳統的全棧開發可以節省更多的時間。
2、多看源碼
原文鏈接:https://www.cnblogs.com/mooremok/p/17003453.html
相關推薦
- 2022-09-04 Go語言中的函數詳解_Golang
- 2022-09-09 Python?cv.Canny()方法參數與使用方法_python
- 2022-11-07 關于react?父子組件的執行順序_React
- 2022-04-21 C++實現MyString的示例代碼_C 語言
- 2022-08-21 Mac包管理器Homebrew的安裝方法_其它綜合
- 2021-12-17 使用遞歸時返回結果是undefined的原因和解決辦法
- 2022-05-16 輕松讀懂Golang中的數組和切片_Golang
- 2022-01-28 Mybatis技術內幕-設計模式與應用場景總結
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支