Django form表單

Django form表單

Form介紹?

我們之前在HTML頁面中利用form表單向后端提交數據時,都會寫一些獲取用戶輸入的標簽并且用form標簽把它們包起來。

與此同時我們在好多場景下都需要對用戶的輸入做校驗,比如校驗用戶是否輸入,輸入的長度和格式等正不正確。如果用戶輸入的內容有錯誤就需要在頁面上相應的位置顯示對應的錯誤信息.。

Django form組件就實現了上面所述的功能。

總結一下,其實form組件的主要功能如下:

  • 生成頁面可用的HTML標簽
  • 對用戶提交的數據進行校驗
  • 保留上次輸入內容
回到頂部

普通方式手寫注冊功能

views.py

復制代碼
# 注冊
def register(request):error_msg = ""if request.method == "POST":username = request.POST.get("name")pwd = request.POST.get("pwd")# 對注冊信息做校驗if len(username) < 6:# 用戶長度小于6位error_msg = "用戶名長度不能小于6位"else:# 將用戶名和密碼存到數據庫return HttpResponse("注冊成功")return render(request, "register.html", {"error_msg": error_msg})
復制代碼

login.html

復制代碼
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>注冊頁面</title>
</head>
<body>
<form action="/reg/" method="post">{% csrf_token %}<p>用戶名:<input type="text" name="name"></p><p>密碼:<input type="password" name="pwd"></p><p><input type="submit" value="注冊"><p style="color: red">{{ error_msg }}</p></p>
</form>
</body>
</html>
復制代碼
回到頂部

使用form組件實現注冊功能

views.py

先定義好一個RegForm類:

from django import forms# 按照Django form組件的要求自己寫一個類
class RegForm(forms.Form):name = forms.CharField(label="用戶名")pwd = forms.CharField(label="密碼")

再寫一個視圖函數:

復制代碼
# 使用form組件實現注冊方式
def register2(request):form_obj = RegForm()if request.method == "POST":# 實例化form對象的時候,把post提交過來的數據直接傳進去form_obj = RegForm(request.POST)# 調用form_obj校驗數據的方法if form_obj.is_valid():return HttpResponse("注冊成功")return render(request, "register2.html", {"form_obj": form_obj})
復制代碼

login2.html

復制代碼
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>注冊2</title>
</head>
<body><form action="/reg2/" method="post" novalidate autocomplete="off">{% csrf_token %}<div><label for="{{ form_obj.name.id_for_label }}">{{ form_obj.name.label }}</label>{{ form_obj.name }} {{ form_obj.name.errors.0 }}</div><div><label for="{{ form_obj.pwd.id_for_label }}">{{ form_obj.pwd.label }}</label>{{ form_obj.pwd }} {{ form_obj.pwd.errors.0 }}</div><div><input type="submit" class="btn btn-success" value="注冊"></div></form>
</body>
</html>
復制代碼

看網頁效果發現 也驗證了form的功能:
? 前端頁面是form類的對象生成的? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? -->生成HTML標簽功能
? 當用戶名和密碼輸入為空或輸錯之后 頁面都會提示? ? ? ? -->用戶提交校驗功能
? 當用戶輸錯之后 再次輸入 上次的內容還保留在input框? ?-->保留上次輸入內容

Form那些事兒

回到頂部

常用字段與插件

創建Form類時,主要涉及到 【字段】 和 【插件】,字段用于對用戶請求數據的驗證,插件用于自動生成HTML;

initial

初始值,input框里面的初始值。

復制代碼
class LoginForm(forms.Form):username = forms.CharField(min_length=8,label="用戶名",initial="張三"  # 設置默認值
    )pwd = forms.CharField(min_length=6, label="密碼")
復制代碼

error_messages

重寫錯誤信息。

復制代碼
class LoginForm(forms.Form):username = forms.CharField(min_length=8,label="用戶名",initial="張三",error_messages={"required": "不能為空","invalid": "格式錯誤","min_length": "用戶名最短8位"})pwd = forms.CharField(min_length=6, label="密碼")
復制代碼

password

復制代碼
class LoginForm(forms.Form):...pwd = forms.CharField(min_length=6,label="密碼",widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True))
復制代碼

radioSelect

單radio值為字符串

復制代碼
class LoginForm(forms.Form):username = forms.CharField(min_length=8,label="用戶名",initial="張三",error_messages={"required": "不能為空","invalid": "格式錯誤","min_length": "用戶名最短8位"})pwd = forms.CharField(min_length=6, label="密碼")gender = forms.fields.ChoiceField(choices=((1, ""), (2, ""), (3, "保密")),label="性別",initial=3,widget=forms.widgets.RadioSelect())
復制代碼

單選Select

復制代碼
class LoginForm(forms.Form):...hobby = forms.fields.ChoiceField(choices=((1, "籃球"), (2, "足球"), (3, "雙色球"), ),label="愛好",initial=3,widget=forms.widgets.Select())
復制代碼

多選Select

復制代碼
class LoginForm(forms.Form):...hobby = forms.fields.MultipleChoiceField(choices=((1, "籃球"), (2, "足球"), (3, "雙色球"), ),label="愛好",initial=[1, 3],widget=forms.widgets.SelectMultiple())
復制代碼

單選checkbox

復制代碼
class LoginForm(forms.Form):...keep = forms.fields.ChoiceField(label="是否記住密碼",initial="checked",widget=forms.widgets.CheckboxInput())
復制代碼

多選checkbox

復制代碼
class LoginForm(forms.Form):...hobby = forms.fields.MultipleChoiceField(choices=((1, "籃球"), (2, "足球"), (3, "雙色球"),),label="愛好",initial=[1, 3],widget=forms.widgets.CheckboxSelectMultiple())
復制代碼

關于choice的注意事項:

在使用選擇標簽時,需要注意choices的選項可以從數據庫中獲取,但是由于是靜態字段 ***獲取的值無法實時更新***,那么需要自定義構造方法從而達到此目的。

方式一:

復制代碼
from django.forms import Form
from django.forms import widgets
from django.forms import fieldsclass MyForm(Form):user = fields.ChoiceField(# choices=((1, '上海'), (2, '北京'),),initial=2,widget=widgets.Select)def __init__(self, *args, **kwargs):super(MyForm,self).__init__(*args, **kwargs)# self.fields['user'].choices = ((1, '上海'), (2, '北京'),)#self.fields['user'].choices = models.Classes.objects.all().values_list('id','caption')
復制代碼

方式二:

復制代碼
from django import forms
from django.forms import fields
from django.forms import models as form_modelclass FInfo(forms.Form):authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all())  # 多選# authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all())  # 單選
復制代碼
回到頂部

Django Form所有內置字段

Fieldrequired=True,               是否允許為空widget=None,                 HTML插件label=None,                  用于生成Label標簽或顯示內容initial=None,                初始值help_text='',                幫助信息(在標簽旁邊顯示)error_messages=None,         錯誤信息 {'required': '不能為空', 'invalid': '格式錯誤'}validators=[],               自定義驗證規則localize=False,              是否支持本地化disabled=False,              是否可以編輯label_suffix=None            Label內容后綴CharField(Field)max_length=None,             最大長度min_length=None,             最小長度strip=True                   是否移除用戶輸入空白IntegerField(Field)max_value=None,              最大值min_value=None,              最小值FloatField(IntegerField)...DecimalField(IntegerField)max_value=None,              最大值min_value=None,              最小值max_digits=None,             總長度decimal_places=None,         小數位長度BaseTemporalField(Field)input_formats=None          時間格式化   DateField(BaseTemporalField)    格式:2015-09-01
TimeField(BaseTemporalField)    格式:11:12
DateTimeField(BaseTemporalField)格式:2015-09-01 11:12DurationField(Field)            時間間隔:%d %H:%M:%S.%f...RegexField(CharField)regex,                      自定制正則表達式max_length=None,            最大長度min_length=None,            最小長度error_message=None,         忽略,錯誤信息使用 error_messages={'invalid': '...'}EmailField(CharField)      ...FileField(Field)allow_empty_file=False     是否允許空文件ImageField(FileField)      ...注:需要PIL模塊,pip3 install Pillow以上兩個字典使用時,需要注意兩點:- form表單中 enctype="multipart/form-data"- view函數中 obj = MyForm(request.POST, request.FILES)URLField(Field)...BooleanField(Field)  ...NullBooleanField(BooleanField)...ChoiceField(Field)...choices=(),                選項,如:choices = ((0,'上海'),(1,'北京'),)required=True,             是否必填widget=None,               插件,默認select插件label=None,                Label內容initial=None,              初始值help_text='',              幫助提示ModelChoiceField(ChoiceField)...                        django.forms.models.ModelChoiceFieldqueryset,                  # 查詢數據庫中的數據empty_label="---------",   # 默認空顯示內容to_field_name=None,        # HTML中value的值對應的字段limit_choices_to=None      # ModelForm中對queryset二次篩選ModelMultipleChoiceField(ModelChoiceField)...                        django.forms.models.ModelMultipleChoiceFieldTypedChoiceField(ChoiceField)coerce = lambda val: val   對選中的值進行一次轉換empty_value= ''            空值的默認值MultipleChoiceField(ChoiceField)...TypedMultipleChoiceField(MultipleChoiceField)coerce = lambda val: val   對選中的每一個值進行一次轉換empty_value= ''            空值的默認值ComboField(Field)fields=()                  使用多個驗證,如下:即驗證最大長度20,又驗證郵箱格式fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])MultiValueField(Field)PS: 抽象類,子類中可以實現聚合多個字典去匹配一個值,要配合MultiWidget使用SplitDateTimeField(MultiValueField)input_date_formats=None,   格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']input_time_formats=None    格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']FilePathField(ChoiceField)     文件選項,目錄下文件顯示在頁面中path,                      文件夾路徑match=None,                正則匹配recursive=False,           遞歸下面的文件夾allow_files=True,          允許文件allow_folders=False,       允許文件夾required=True,widget=None,label=None,initial=None,help_text=''GenericIPAddressFieldprotocol='both',           both,ipv4,ipv6支持的IP格式unpack_ipv4=False          解析ipv4地址,如果是::ffff:192.0.2.1時候,可解析為192.0.2.1, PS:protocol必須為both才能啟用SlugField(CharField)           數字,字母,下劃線,減號(連字符)...UUIDField(CharField)           uuid類型
Django Form內置字段
回到頂部

校驗

方式一:

復制代碼
from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.validators import RegexValidatorclass MyForm(Form):user = fields.CharField(validators=[RegexValidator(r'^[0-9]+$', '請輸入數字'), RegexValidator(r'^159[0-9]+$', '數字必須以159開頭')],)
復制代碼

方式二:

復制代碼
import re
from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.exceptions import ValidationError# 自定義驗證規則
def mobile_validate(value):mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')if not mobile_re.match(value):raise ValidationError('手機號碼格式錯誤')class PublishForm(Form):title = fields.CharField(max_length=20,min_length=5,error_messages={'required': '標題不能為空','min_length': '標題最少為5個字符','max_length': '標題最多為20個字符'},widget=widgets.TextInput(attrs={'class': "form-control",'placeholder': '標題5-20個字符'}))# 使用自定義驗證規則phone = fields.CharField(validators=[mobile_validate, ],error_messages={'required': '手機不能為空'},widget=widgets.TextInput(attrs={'class': "form-control",'placeholder': u'手機號碼'}))email = fields.EmailField(required=False,error_messages={'required': u'郵箱不能為空','invalid': u'郵箱格式錯誤'},widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'郵箱'}))
復制代碼
回到頂部

補充進階

應用Bootstrap樣式

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="x-ua-compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"><title>login</title>
</head>
<body>
<div class="container"><div class="row"><form action="/login2/" method="post" novalidate class="form-horizontal">{% csrf_token %}<div class="form-group"><label for="{{ form_obj.username.id_for_label }}"class="col-md-2 control-label">{{ form_obj.username.label }}</label><div class="col-md-10">{{ form_obj.username }}<span class="help-block">{{ form_obj.username.errors.0 }}</span></div></div><div class="form-group"><label for="{{ form_obj.pwd.id_for_label }}" class="col-md-2 control-label">{{ form_obj.pwd.label }}</label><div class="col-md-10">{{ form_obj.pwd }}<span class="help-block">{{ form_obj.pwd.errors.0 }}</span></div></div><div class="form-group"><label class="col-md-2 control-label">{{ form_obj.gender.label }}</label><div class="col-md-10"><div class="radio">{% for radio in form_obj.gender %}<label for="{{ radio.id_for_label }}">{{ radio.tag }}{{ radio.choice_label }}</label>{% endfor %}</div></div></div><div class="form-group"><div class="col-md-offset-2 col-md-10"><button type="submit" class="btn btn-default">注冊</button></div></div></form></div>
</div><script src="/static/jquery-3.2.1.min.js"></script>
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
Django form應用Bootstrap樣式簡單示例

批量添加樣式

可通過重寫form類的init方法來實現。

class LoginForm(forms.Form):username = forms.CharField(min_length=8,label="用戶名",initial="張三",error_messages={"required": "不能為空","invalid": "格式錯誤","min_length": "用戶名最短8位"}...def __init__(self, *args, **kwargs):super(LoginForm, self).__init__(*args, **kwargs)for field in iter(self.fields):self.fields[field].widget.attrs.update({'class': 'form-control'})
批量添加樣式

ModelForm

form與model的終極結合。

復制代碼
class BookForm(forms.ModelForm):class Meta:model = models.Bookfields = "__all__"labels = {"title": "書名","price": "價格"}widgets = {"password": forms.widgets.PasswordInput(attrs={"class": "c1"}),}
復制代碼

?class Meta:下常用參數:

復制代碼
model = models.Student  # 對應的Model中的類
fields = "__all__"  # 字段,如果是__all__,就是表示列出所有的字段
exclude = None  # 排除的字段
labels = None  # 提示信息
help_texts = None  # 幫助提示信息
widgets = None  # 自定義插件
error_messages = None  # 自定義錯誤信息
復制代碼

轉載于:https://www.cnblogs.com/chenyibai/p/9807131.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/279159.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279159.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279159.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

java 多線程 優先級_java多線程之線程的優先級

在操作系統中&#xff0c;線程可以劃分優先級&#xff0c;優先級較高的線程得到CPU資源較多&#xff0c;也就是CPU優先執行優先級較高的線程對象中的任務(其實并不是這樣)。在java中&#xff0c;線程的優先級用setPriority()方法就行&#xff0c;線程的優先級分為1-10這10個等級…

PyQt5應用與實踐

2015-01-16 19:00 by 吳秦, 69476 閱讀, 5 評論, 收藏, 編輯 一個典型的GUI應用程序可以抽象為&#xff1a;主界面&#xff08;菜單欄、工具欄、狀態欄、內容區域&#xff09;&#xff0c;二級界面&#xff08;模態、非模態&#xff09;&#xff0c;信息提示&#xff08;Toolti…

plex實現流媒體服務器_Plex繼續遠離服務器,提供網絡節目

plex實現流媒體服務器() Plex now offers a “Web Shows” feature in certain versions of their interface, providing access to shows from brands like TWiT, GQ, and Popular Science. Plex現在在其界面的某些版本中提供了“網絡節目”功能&#xff0c;可以訪問TWiT&…

MIME協議(三) -- MIME郵件的組織結構

一封MIME郵件可以由多個不同類型的MIME消息組合而成&#xff0c;一個MIME消息表示郵件中的一個基本MIME資源或若干基本MIME消息的組合體。每個MIME消息的數據格式與RFC822數據格式相似&#xff0c;也包括頭和體兩部分&#xff0c;分別稱為MIME消息頭和MIME消息體&#xff0c;它…

discord linux_最好的Discord機器人來啟動服務器

discord linuxDiscord has an extensive API and good support for bots on their platform. Because of this, there are tons of bots to go around. However, many of them just copy one another’s functionality. We’ve picked out the ones that do it right, and comp…

java獲取前端json數據_java如何獲取前端ajax傳來的json對象

假設使用 jQuery 中的 ajax1. Json 對象前端代碼示例$.ajax({url : http://localhost:8888/demo,type: post,data: {userName:15488779956}success: function(data) {// TODO}})后臺代碼示例RestControllerpublic class Demo {/*** 方法 1 使用 HttpServletRequest 接收* */Req…

版本控制介紹以及常用的版本控制工具

版本控制是指對軟件開發過程中各種程序代碼、配置文件及說明文檔等文件變更的管理&#xff0c;是軟件配置管理的核心思想之一。 編寫一個成熟可用的程序是一個工作量很大的工程&#xff0c;并非我們一次性就可以搞定的工作&#xff0c;所以在開發過程當中需要&#xff1a; 1、 …

2019年4月第四周_2012年4月最佳怪胎文章

2019年4月第四周This past month we covered topics such as how to use a 64-bit web browser on Windows, the best tips and tweaks for getting the most out of Firefox, how to check out library books on your Kindle for free, and more. Join us as we look back at …

matlab循環遍歷數組_Matlab - 訪問for循環中最大值的索引,并使用它從數組中刪除值...

我想遞歸地找到一系列矩陣中的最大值(第8列&#xff0c;具體)&#xff0c;然后使用該最大值的索引來設置數組中的所有值&#xff0c;索引最大為NaN的最大索引(對于列14:16) . 很容易找到最大值和索引&#xff0c;但是使用for循環為多個數組做這件事我很難過 .如果沒有for循環&a…

【資料整理】編譯安裝nginx

【nginx】編譯安裝nginx 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311…

游蕩的奶牛

沙雕題目 讀錯題了&#xff0c;不想多說 轉載于:https://www.cnblogs.com/bullshit/p/9811058.html

物體成癮性_科技成癮使我們不那么快樂。 那是一個市場機會。

物體成癮性Compulsively checking social networks makes us less happy. I think we all understand this intuitively, the same way we understand that working out more and eating better is a good idea. 強迫檢查社交網絡使我們不那么開心。 我認為我們所有人都可以憑直…

mysql 不要統計null_淺談為什么Mysql數據庫盡量避免NULL

在Mysql中很多表都包含可為NULL(空值)的列&#xff0c;即使應用程序并不需要保存NULL也是如此&#xff0c;這是因為可為NULL是列的默認屬性。但我們常在一些Mysql性能優化的書或者一些博客中看到觀點&#xff1a;在數據列中&#xff0c;盡量不要用NULL 值&#xff0c;使用0&…

Swing學習1——總體概述

以下來自于JDK1.6 一、Swing學習我劃分為兩個方面&#xff1a; 一方面Swing的界面設計部分&#xff0c;包括相關組件類的繼承關系&#xff0c;組件的功能用途&#xff0c;布局管理&#xff1b; 1.首先繼承關系上自上而下為 java.lang.Object java.awt.Component java.awt.Conta…

裝飾設計模式和例題

文件復制程序&#xff1a; 將一個文件復制一份出來&#xff0c;實現方法很簡單&#xff0c;使用FileInputStream讀取文件內容&#xff0c;然后使用FileOutputStream寫入另一個文件&#xff0c;利用read方法的返回值作為while循環的條件&#xff0c;進行一邊讀一邊寫。 代碼示例…

mysql操作手冊我_MySQL使用指南一

我將MySQL常用指令整理出來分享給大家。1. 列出所有數據庫mysql> show databases;2. 創建數據庫mysql> create databases MyStorage;3. 打開數據庫mysql> use MyStorage;4. 創建表mysql> create table Storage-> (-> id int,-> name varchar(50),-> pr…

谷歌地圖將很快顯示電動汽車充電站

If you’re out on the road in the future and find your electric vehicle is in dire need of a charge, you’ll soon be able to look to Google Maps for help finding a charging station. 如果您將來出門在外&#xff0c;并且發現您的電動汽車急需充電&#xff0c;那么…

JS4

1. js的本質就是處理數據。數據來自于后臺的數據庫。 所以變量就起到一個臨時存儲數據的作用。 ECMAScript制定了js的數據類型。 數據類型有哪些&#xff1f; 字符串 String數字 Number布爾 BooleanNull 空Undefined Object 對象Array 數組 json function …

ovirt官方安裝文檔 第三章

第3章&#xff1a;安裝oVirt 安裝oVirt引擎包 在您可以配置和使用oVirt引擎之前&#xff0c;您必須安裝 rhevm 包和依賴關系。 安裝oVirt引擎包 在開始安裝oVirt之前&#xff0c;添加官方倉庫&#xff1a; # yum install http://resources.ovirt.org/pub/yum-repo/ovirt-releas…

mysql獲取查詢策略語句_MySQL數據庫查詢性能優化策略

優化查詢使用Explain語句分析查詢語句Explain 用來分析 SELECT 查詢語句&#xff0c;開發人員可以通過分析 Explain 結果來優化查詢語句。通過對查詢語句的分析,可以了解查詢語句的執行情況,找出查詢語句執行的瓶頸,從而優化查詢語句.使用索引查詢MySql中提高性能的一個最有效的…