Django-forms組件

一 forms組件css

-forms是什麼? 就是一個類,能夠校驗字段(前臺傳過來的字段) -怎麼用: -校驗字段功能: -先寫一個類,繼承Form from django.shortcuts import render, HttpResponse from django import forms # 寫一個類,要校驗那些字段,就是類的屬性
            class MyForm(forms.Form): # 定義一個屬性,能夠用來校驗字符串類型
                # 限制最大長度是8,最小長度是3
                name=forms.CharField(max_length=8,min_length=3) pwd=forms.CharField(max_length=8,min_length=3,required=True) # 校驗是不是郵箱格式
                email=forms.EmailField() -使用: #實例化產生對象,傳入要校驗的數據(字典)
                myform=MyForm(request.POST) # is_valid若是是true表示校驗成功,反之,校驗失敗
                if myform.is_valid(): # 校驗經過的數據
                    print(myform.cleaned_data) return HttpResponse('校驗成功') else: print(myform.cleaned_data) #校驗失敗的信息
                    print(myform.errors) -注意:校驗的字段,能夠多,可是不能少

二 渲染模板html

第一中方式:(靈活性最高) <form action="" method="post" >
                    <p>用戶名: {{ myform.name }}</p>
                    <p>密碼: {{ myform.pwd }}</p>
                    <p>郵箱: {{ myform.email }}</p>
                    <input type="submit" value="提交">
                </form>
第二種方式:for循環form對象(用的比較多): <form action="" method="post" > {% for foo in myform %} <p>{{ foo.label }}:{{ foo }}</p> {% endfor %} <input type="submit" value="提交">
                </form>
第三種方式(不建議用): <form action="" method="post" >   {#{{ myform.as_p }}#}
 {{ myform.as_ul }} <input type="submit" value="提交">
                </form>

三 渲染錯誤信息jquery

- myforms有errors -屬性(name)也有errors -錯誤信息,變成中文: - error_messages={'max_length': '最長是8', 'min_length': '最短是3', 'required': '這個必須填','invalid': '不符合郵箱格式'} -給input標籤指定樣式,指定格式: - widget=widgets.TextInput(attrs={'class':'form-control'}) -模板,渲染錯誤信息:<span>{{ myform.name.errors.0 }}</span>

四 局部鉤子與全局鉤子django

-局部鉤子校驗 -定義一個函數,名字叫:clean_字段名字,內部,取出該字段,進行校驗,若是經過,將該字段返回,若是失敗,拋異常(ValidationError) def clean_name(self): # self:當前form對象
        name = self.cleaned_data.get('name') if name.startswith('sb'): # 失敗,拋異常
            raise ValidationError('名字不能以傻逼開頭') if models.User.objects.filter(name=name).first(): raise ValidationError('此用戶名已被使用') return name -全局鉤子 #重寫clean方法
    def clean(self): #程序能走到該函數,前面校驗已經經過了,因此能夠從cleaned_data中取出密碼和確認密碼 
        pwd = self.cleaned_data.get('pwd') re_pwd = self.cleaned_data.get('re_pwd') #進行本身的校驗
        if pwd == re_pwd: #經過,直接返回cleaned_data
            return self.cleaned_data else: #失敗,拋異常(ValidationError)
            raise ValidationError('兩次密碼不一致') 

 五 註冊bootstrap

from django.db import models # Create your models here.
class User(models.Model): name = models.CharField(max_length=32) pwd = models.CharField(max_length=32) phone = models.CharField(max_length=32) email = models.EmailField()
models.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="/static/bootstrap-3.3.7-dist/js/jquery-3.3.1.min.js"></script>
    <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    <title>Title</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-4 col-md-offset-3">
            <form action="" method="post" class="form-horizontal" novalidate>
                <div class="form-group"> {% for foo in myform %} <label for="inputEmail3" class="col-sm-4 control-label">{{ foo.label }}:</label>
                        <div class="col-sm-8"><p>{{ foo }} <span style="color: red">{{ foo.errors.0 }}</span></p></div> {% endfor %} <input type="submit" value="註冊" class="col-md-offset-7 btn btn-primary"><span style="color: red">{{ all_error }}</span>
                </div>
            </form>
        </div>
    </div>
</div>

</body>
</html>
index.html
from django.shortcuts import render, redirect, HttpResponse from django.http import JsonResponse from app01 import models from django import forms from django.forms import widgets from django.core.exceptions import ValidationError # Create your views here.

class MyForm(forms.Form): name = forms.CharField(max_length=8, min_length=3, label='用戶名', error_messages={'max_length': '用戶名最長是8位', 'min_length': '用戶名最短是3位', 'required': '此項爲必填項'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'id': 'name'})) pwd = forms.CharField(max_length=16, min_length=6, label='密碼', error_messages={'max_length': '密碼最長是16位', 'min_length': '用戶名最短是6位', 'required': '此項爲必填項'}, widget=widgets.PasswordInput(attrs={'class': 'form-control', 'id': 'pwd'})) re_pwd = forms.CharField(max_length=16, min_length=6, label='確認密碼', error_messages={'max_length': '密碼最長是16位', 'min_length': '用戶名最短是6位', 'required': '此項爲必填項'}, widget=widgets.PasswordInput(attrs={'class': 'form-control', 'id': 're_pwd'})) phone = forms.CharField(label='手機號', error_messages={'required': '此項爲必填項'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'id': 'phone'})) email = forms.EmailField(label='郵箱', widget=widgets.TextInput(attrs={'class': 'form-control', 'id': 'email'}), error_messages={'required': '此項爲必填項', 'invalid': '不符合郵箱格式'}) def clean_name(self): name = self.cleaned_data.get('name') if name.startswith('sb'): raise ValidationError('名字不能以傻逼開頭') if models.User.objects.filter(name=name).first(): raise ValidationError('此用戶名已被使用') return name def clean_phone(self): phone = self.cleaned_data.get('phone') if models.User.objects.filter(phone=phone).first(): raise ValidationError('此號碼已被註冊過,請更換號碼') if len(phone) != 11: raise ValidationError('請填寫正確的手機號') return phone def clean_email(self): email = self.cleaned_data.get('phone') if models.User.objects.filter(email=email).first(): raise ValidationError('此郵箱已被註冊過,請更換郵件') return email def clean(self): pwd = self.cleaned_data.get('pwd') re_pwd = self.cleaned_data.get('re_pwd') if pwd == re_pwd: return self.cleaned_data else: raise ValidationError('兩次密碼不一致') def index(request): if request.method == 'GET': myform = MyForm() if request.method == 'POST': myform = MyForm(request.POST) if myform.is_valid(): myform.cleaned_data.pop('re_pwd') models.User.objects.create(**myform.cleaned_data) return redirect('http://baidu.com') else: all_error = myform.errors.get('__all__') if all_error: all_error = all_error[0] return render(request, 'index.html', locals())
views.py
相關文章
相關標籤/搜索