日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Django基础11(Django中form表单)

發(fā)布時(shí)間:2023/12/10 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Django基础11(Django中form表单) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Form介紹?

  之前在HTML頁面中利用form表單向后端提交數(shù)據(jù)時(shí),都會(huì)寫一些獲取用戶輸入的標(biāo)簽并且用form標(biāo)簽把它們包起來。

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

Django form組件就實(shí)現(xiàn)了上面所述的功能。

總結(jié)一下,其實(shí)form組件的主要功能如下:

  • 生成頁面可用的HTML標(biāo)簽
  • 對用戶提交的數(shù)據(jù)進(jìn)行校驗(yàn)
  • 保留上次輸入內(nèi)容

普通的登錄

views.py

def login(request):error_msg = ""if request.method == "POST":username = request.POST.get("username")pwd = request.POST.get("pwd")if username == "SKS" and pwd == "1366768":return HttpResponse("OK")else:error_msg = "用戶名或密碼錯(cuò)誤"return render(request, "login.html", {"error_msg": error_msg})

login.html

<!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"><title>login</title><style>.error {color: red;}</style> </head> <body> <form action="/login/" method="post">{% csrf_token %}<p><label for="username">用戶名</label><input type="text" name="username" id="username"></p><p><label for="pwd">密碼</label><input type="password" name="pwd" id="pwd"><span class="error"></span></p><p><input type="submit"><span class="error">{{ error_msg }}</span></p> </form> </body> </html>

使用form組件

views.py

先定義好一個(gè)LoginForm類。

# 定義一個(gè)form組件類 class LoginForm(forms.Form):# 驗(yàn)證的字段及條件username = forms.CharField(min_length=8, label="用戶名")pwd = forms.CharField(min_length=6, label="密碼")def login2(request):# 存儲錯(cuò)誤信息error_msg = ""# 實(shí)例化對象form_obj = LoginForm()# 判斷前端頁面請求是否是POST請求if request.method == "POST":# 將數(shù)據(jù)傳入form組件類中form_obj = LoginForm(request.POST)# 存儲的正確信息if form_obj.is_valid():username = form_obj.cleaned_data.get("username")pwd = form_obj.cleaned_data.get("pwd")if username == "SKS" and pwd == "1866768":return HttpResponse("OK")else:error_msg = "用戶名或密碼錯(cuò)誤"return render(request, "login2.html", {"form_obj": form_obj, "error_msg": error_msg})

login2.html

<!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"><title>login</title><style>.error {color: red;}</style> </head> <body> <form action="/login2/" method="post" novalidate>{% csrf_token %}<p>{{ form_obj.username.label }}{{ form_obj.username }}<span class="error">{{ form_obj.username.errors.0 }}</span></p><p>{{ form_obj.pwd.label }}{{ form_obj.pwd }}<span class="error">{{ form_obj.pwd.errors.0 }}</span></p><p><input type="submit"><span class="error">{{ error_msg }}</span></p> </form> </body> </html>

看網(wǎng)頁效果發(fā)現(xiàn) 也驗(yàn)證了form的功能:
? 前端頁面是form類的對象生成的? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? -->生成HTML標(biāo)簽功能
? 當(dāng)用戶名和密碼輸入為空或輸錯(cuò)之后 頁面都會(huì)提示? ? ? ? -->用戶提交校驗(yàn)功能
? 當(dāng)用戶輸錯(cuò)之后 再次輸入 上次的內(nèi)容還保留在input框? ?-->保留上次輸入內(nèi)容

Form組件

常用字段演示

initial

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

# 定義一個(gè)類繼承forms.Form class LoginForm(forms.Form):username = forms.CharField(min_length=6,label="用戶名",initial="hewm" # 設(shè)置默認(rèn)值方法 )pwd = forms.CharField(min_length=6, label="密碼")

error_messages

重寫錯(cuò)誤信息。

class LoginForm(forms.Form):username = forms.CharField(min_length=6,label="用戶名",initial="hewm",# 重寫錯(cuò)誤提示信息error_messages={"required": "不能為空","invalid": "格式錯(cuò)誤","min_length": "用戶名最短6位"})pwd = forms.CharField(min_length=6, label="密碼")

password

class LoginForm(forms.Form):...pwd = forms.CharField(min_length=6,label="密碼",
# 密文方法 參數(shù)
attrs:樣式類 render_value=驗(yàn)證失敗是否回填 widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True) )

radioSelect

單radio值為字符串

class LoginForm(forms.Form):username = forms.CharField(min_length=8,label="用戶名",initial="hewm",error_messages={"required": "不能為空","invalid": "格式錯(cuò)誤","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)

關(guān)于choice的注意事項(xiàng):

在使用選擇標(biāo)簽時(shí),需要注意choices的選項(xiàng)可以從數(shù)據(jù)庫中獲取,但是由于是靜態(tài)字段 ***獲取的值無法實(shí)時(shí)更新***,那么需要自定義構(gòu)造方法從而達(dá)到此目的。

方式一:

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)# 初始化init方法 (執(zhí)行時(shí)間為類實(shí)例化時(shí)執(zhí)行)def __init__(self, *args, **kwargs):super(MyForm,self).__init__(*args, **kwargs)# self.fields['user'].widget.choices = ((1, '上海'), (2, '北京'),)#self.fields['user'].widget.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()) Fieldrequired=True, 是否允許為空widget=None, HTML插件label=None, 用于生成Label標(biāo)簽或顯示內(nèi)容initial=None, 初始值help_text='', 幫助信息(在標(biāo)簽旁邊顯示)error_messages=None, 錯(cuò)誤信息 {'required': '不能為空', 'invalid': '格式錯(cuò)誤'}show_hidden_initial=False, 是否在當(dāng)前插件后面再加一個(gè)隱藏的且具有默認(rèn)值的插件(可用于檢驗(yàn)兩次輸入是否一直)validators=[], 自定義驗(yàn)證規(guī)則localize=False, 是否支持本地化disabled=False, 是否可以編輯label_suffix=None Label內(nèi)容后綴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, 小數(shù)位長度BaseTemporalField(Field)input_formats=None 時(shí)間格式化 DateField(BaseTemporalField) 格式:2015-09-01 TimeField(BaseTemporalField) 格式:11:12 DateTimeField(BaseTemporalField)格式:2015-09-01 11:12DurationField(Field) 時(shí)間間隔:%d %H:%M:%S.%f...RegexField(CharField)regex, 自定制正則表達(dá)式max_length=None, 最大長度min_length=None, 最小長度error_message=None, 忽略,錯(cuò)誤信息使用 error_messages={'invalid': '...'}EmailField(CharField) ...FileField(Field)allow_empty_file=False 是否允許空文件ImageField(FileField) ...注:需要PIL模塊,pip3 install Pillow以上兩個(gè)字典使用時(shí),需要注意兩點(diǎn):- form表單中 enctype="multipart/form-data"- view函數(shù)中 obj = MyForm(request.POST, request.FILES)URLField(Field)...BooleanField(Field) ...NullBooleanField(BooleanField)...ChoiceField(Field)...choices=(), 選項(xiàng),如:choices = ((0,'上海'),(1,'北京'),)required=True, 是否必填widget=None, 插件,默認(rèn)select插件label=None, Label內(nèi)容initial=None, 初始值help_text='', 幫助提示ModelChoiceField(ChoiceField)... django.forms.models.ModelChoiceFieldqueryset, # 查詢數(shù)據(jù)庫中的數(shù)據(jù)empty_label="---------", # 默認(rèn)空顯示內(nèi)容to_field_name=None, # HTML中value的值對應(yīng)的字段limit_choices_to=None # ModelForm中對queryset二次篩選 ModelMultipleChoiceField(ModelChoiceField)... django.forms.models.ModelMultipleChoiceFieldTypedChoiceField(ChoiceField)coerce = lambda val: val 對選中的值進(jìn)行一次轉(zhuǎn)換empty_value= '' 空值的默認(rèn)值MultipleChoiceField(ChoiceField)...TypedMultipleChoiceField(MultipleChoiceField)coerce = lambda val: val 對選中的每一個(gè)值進(jìn)行一次轉(zhuǎn)換empty_value= '' 空值的默認(rèn)值ComboField(Field)fields=() 使用多個(gè)驗(yàn)證,如下:即驗(yàn)證最大長度20,又驗(yàn)證郵箱格式fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])MultiValueField(Field)PS: 抽象類,子類中可以實(shí)現(xiàn)聚合多個(gè)字典去匹配一個(gè)值,要配合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) 文件選項(xiàng),目錄下文件顯示在頁面中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時(shí)候,可解析為192.0.2.1, PS:protocol必須為both才能啟用SlugField(CharField) 數(shù)字,字母,下劃線,減號(連字符)...UUIDField(CharField) uuid類型Django form內(nèi)置字段 內(nèi)置字段

校驗(yàn)

方式一:

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]+$', '請輸入數(shù)字'), RegexValidator(r'^159[0-9]+$', '數(shù)字必須以159開頭')],)

方式二:

import re from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.exceptions import ValidationError# 自定義驗(yàn)證規(guī)則 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('手機(jī)號碼格式錯(cuò)誤')class PublishForm(Form):title = fields.CharField(max_length=20,min_length=5,error_messages={'required': '標(biāo)題不能為空','min_length': '標(biāo)題最少為5個(gè)字符','max_length': '標(biāo)題最多為20個(gè)字符'},widget=widgets.TextInput(attrs={'class': "form-control",'placeholder': '標(biāo)題5-20個(gè)字符'}))# 使用自定義驗(yàn)證規(guī)則phone = fields.CharField(validators=[mobile_validate, ],error_messages={'required': '手機(jī)不能為空'},widget=widgets.TextInput(attrs={'class': "form-control",'placeholder': u'手機(jī)號碼'}))email = fields.EmailField(required=False,error_messages={'required': u'郵箱不能為空','invalid': u'郵箱格式錯(cuò)誤'},widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'郵箱'}))

補(bǔ)充進(jìn)階

應(yīng)用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應(yīng)用Bootstrap樣式簡單示例 代碼示例

批量添加樣式

可通過重寫form類的init方法來實(shí)現(xiàn)。

class LoginForm(forms.Form):username = forms.CharField(min_length=8,label="用戶名",initial="張三",error_messages={"required": "不能為空","invalid": "格式錯(cuò)誤","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'})批量添加樣式 代碼示例

源碼簡易剖析

views.py文件

def register(request):if request.method == "POST":res = {"user": None, "error_dict": None}form = RegForm(request.POST)# 存儲驗(yàn)證通過的信息.is_valid()(源碼剖析開始點(diǎn))if form.is_valid():user = form.cleaned_data.get("user")pwd = form.cleaned_data.get("pwd")email = form.cleaned_data.get("email")avatar = request.FILES.get("avatar")print(user,pwd,email,avatar)print("="*120)if avatar:user = UserInfo.objects.create_user(username=user, password=pwd, email=email, avatar=avatar)else:user = UserInfo.objects.create_user(username=user, password=pwd, email=email)res["user"] = user.usernameelse:print(form.errors)res["error_dict"] = form.errorsreturn JsonResponse(res)form = RegForm()return render(request, 'register.html', locals()) views.py

點(diǎn)擊進(jìn)入forms.py文件

def is_valid(self):"""Returns True if the form has no errors. Otherwise, False. If errors arebeing ignored, returns False."""# 含義:返回布爾值,只要有數(shù)據(jù)并且沒有錯(cuò)誤信息就返回Truereturn self.is_bound and not self.errors forms.py

點(diǎn)擊self.errors進(jìn)入forms.py文件中

# 靜態(tài)方法 @propertydef errors(self):"Returns an ErrorDict for the data provided for the form"# 判斷self._errors是否為空if self._errors is None:self.full_clean()return self._errors def errors(self):

點(diǎn)擊._errors進(jìn)入forms.py文件中

def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,initial=None, error_class=ErrorList, label_suffix=None,empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None):self.is_bound = data is not None or files is not Noneself.data = data or {}self.files = files or {}self.auto_id = auto_idif prefix is not None:self.prefix = prefixself.initial = initial or {}self.error_class = error_class# Translators: This is the default suffix added to form field labelsself.label_suffix = label_suffix if label_suffix is not None else _(':')self.empty_permitted = empty_permitted# 默認(rèn)值為Noneself._errors = None # Stores the errors after clean() has been called.# The base_fields class attribute is the *class-wide* definition of# fields. Because a particular *instance* of the class might want to# alter self.fields, we create self.fields here by copying base_fields.# Instances should always modify self.fields; they should not modify# self.base_fields.self.fields = copy.deepcopy(self.base_fields)self._bound_fields_cache = {}self.order_fields(self.field_order if field_order is None else field_order) __init__方法

返回def errors(self):

@propertydef errors(self):"Returns an ErrorDict for the data provided for the form"if self._errors is None:self.full_clean() # 這個(gè)方法才是真正幫忙執(zhí)行效驗(yàn)操作return self._errors 返回errors方法

點(diǎn)擊

def full_clean(self):"""Cleans all of self.data and populates self._errors andself.cleaned_data."""self._errors = ErrorDict() # 定義一個(gè)保存錯(cuò)誤信息字典if not self.is_bound: # Stop further processing.returnself.cleaned_data = {}# If the form is permitted to be empty, and none of the form data has# changed from the initial data, short circuit any validation.if self.empty_permitted and not self.has_changed():returnself._clean_fields()self._clean_form()self._post_clean() full_clean方法

點(diǎn)擊self._clean_fields()進(jìn)入

def _clean_fields(self):for name, field in self.fields.items():# self.fields:類似一個(gè)字典#for name, field in self.fields.items():解釋分別獲取self.fields的鍵和值分別賦值給 name, field# value_from_datadict() gets the data from the data dictionaries.# Each widget type knows how to retrieve its own data, because some# widgets split data over several HTML fields.if field.disabled:value = self.get_initial_for_field(field, name)else:value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))try:if isinstance(field, FileField): # 如果是文件字段initial = self.get_initial_for_field(field, name)value = field.clean(value, initial)else: # field.clean(value) 之后Dbug運(yùn)行檢查,為循環(huán)判斷錯(cuò)誤value = field.clean(value)self.cleaned_data[name] = valueif hasattr(self, 'clean_%s' % name):value = getattr(self, 'clean_%s' % name)()self.cleaned_data[name] = valueexcept ValidationError as e:self.add_error(name, e) def _clean_fields(self):方法

06后期追加

?

轉(zhuǎn)載于:https://www.cnblogs.com/L5251/articles/8792927.html

總結(jié)

以上是生活随笔為你收集整理的Django基础11(Django中form表单)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。