溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

6.分頁(yè),form組件

發(fā)布時(shí)間:2020-07-06 19:55:48 來(lái)源:網(wǎng)絡(luò) 閱讀:445 作者:DevOperater 欄目:編程語(yǔ)言

1.分頁(yè)功能

1.1批量插入數(shù)據(jù)

# 批量插入數(shù)據(jù)
    book_list = []
    for i in range(100):
        book = Book(title="book_%s"%i,price=i*i,publishDate="2012-12-12",publish_id=1)
        book_list.append(book)
    Book.objects.bulk_create(book_list)

1.2Paginator

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

    book_list = Book.objects.all()
    paginator = Paginator(book_list, 10)  # 每頁(yè)顯示10條數(shù)據(jù)
    print(paginator.count)  # 總數(shù)據(jù)數(shù)  105
    print(paginator.num_pages)  # 總頁(yè)數(shù)  11
    print(paginator.page_range)  # 頁(yè)碼的列表  range(1, 12)
    page1 = paginator.page(1)  # 第一頁(yè)的book對(duì)象列表
    print(page1)  # <Page 1 of 11>
    for i in page1:  # 遍歷第一頁(yè)的所有數(shù)據(jù)對(duì)象
        print(i)  # Book object (16)
    print(page1.object_list)  # 第一頁(yè)的所有數(shù)據(jù)[<Book: Book object (7)>, ... <Book: Book object (16)>]

    page2 = paginator.page(2)
    print(page2.has_next())  # 是否有下一頁(yè) True
    print(page2.next_page_number())  # 下一頁(yè)的頁(yè)碼 3
    print(page2.has_previous())  # 是否有上一頁(yè) True
    print(page2.previous_page_number())  # 上一頁(yè)的頁(yè)碼 1

        # 拋錯(cuò)
    page=paginator.page(12)   # error:EmptyPage

    page=paginator.page("z")   # error:PageNotAnInteger

1.3分頁(yè)案例

views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage
from app1.models import *
def index(request):
    book_list = Book.objects.all()
    paginator = Paginator(book_list, 7)  # 每頁(yè)顯示7條數(shù)據(jù)
    current_page = int(request.GET.get("page", 1))  # 沒(méi)有page這個(gè)key,就設(shè)置為1

# 這里是保證當(dāng)前最多只顯示11個(gè)頁(yè)碼
    if paginator.num_pages > 11:
        if current_page-5<1:
            page_range = range(1,12)
        elif current_page+5>paginator.num_pages:
            page_range = range(paginator.num_pages-10,paginator.num_pages+1)
        else:
            page_range = range(current_page - 5, current_page + 6)
    else:
        page_range = paginator.page_range

    # 顯示當(dāng)前頁(yè)的book對(duì)象列表
    try:
        current_page_contents = paginator.page(current_page)
    #     如果數(shù)據(jù)為空,顯示第一頁(yè)的數(shù)據(jù)
    except EmptyPage as e:
        current_page_contents = paginator.page(1)

    return render(request, "index.html",locals())

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh5u" crossorigin="anonymous">
    <script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<ul>
    {% for book_obj in current_page_contents %}
        <li>{{ book_obj.title }}--{{ book_obj.price }}</li>
    {% endfor %}

</ul>

<nav aria-label="Page navigation">
  <ul class="pagination">

{#    當(dāng)前頁(yè)有上一頁(yè)的時(shí)候,才可點(diǎn)擊#}
        {% if current_page_contents.has_previous %}
            <li><a href="?page={{ current_page_contents.previous_page_number }}" aria-label="Previous">
            <span aria-hidden="true">上一頁(yè)</span>
            </a></li>
        {% else %}
            <li class="disabled"><a href="" aria-label="Previous" >
            <span aria-hidden="true">上一頁(yè)</span>
            </a></li>
        {% endif %}

      {% for page_num in page_range %}
{#          前面的內(nèi)容就是當(dāng)前訪問(wèn)的url#}
          {% if page_num == current_page %}
              <li class="active"><a href="?page={{ page_num }}">{{ page_num }}</a></li>
          {% else %}
              <li><a href="?page={{ page_num }}">{{ page_num }}</a></li>
          {% endif %}

      {% endfor %}

        {% if current_page_contents.has_next %}
            <li><a href="?page={{ current_page_contents.next_page_number }}" aria-label="Next">
                <span aria-hidden="true">下一頁(yè)</span>
            </a></li>
        {% else %}
            <li class="disabled"><a href="" aria-label="Next">
                <span aria-hidden="true">下一頁(yè)</span>
            </a></li>
        {% endif %}

  </ul>
</nav>

</body>
<script type="text/javascript">

</script>
</html>

6.分頁(yè),form組件
6.分頁(yè),form組件
6.分頁(yè),form組件

2.forms組件

作用:
主要是校驗(yàn)字段功能

2.1簡(jiǎn)單form

注意:
1.即使不是所有字段驗(yàn)證通過(guò),form.cleaned_data中也有通過(guò)驗(yàn)證的字段的值。
2.前端傳過(guò)來(lái)的字段可以比UserForm中的字段多,多余的字段不進(jìn)行驗(yàn)證。所有字段驗(yàn)證通過(guò),form.is_valid()返回true。
3.前端傳過(guò)來(lái)的字段比UserForm中的字段少,form.is_valid()返回false。

forms.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
from django import forms
class UserForm(forms.Form):
    name = forms.CharField(min_length=4, label="用戶名", error_messages={"required": "該字段不能為空"})
    pwd = forms.CharField(min_length=4, label="密碼", error_messages={"required": "該字段不能為空"})
    r_pwd = forms.CharField(min_length=4, label="確認(rèn)密碼", error_messages={"required": "該字段不能為空"})
    email = forms.EmailField(label="郵箱" , error_messages={"required": "該字段不能為空", "invalid": "格式錯(cuò)誤"})
    tel = forms.CharField(label="手機(jī)號(hào)")

views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage
from app1.models import *
from app1.myforms import *
def index(request):
    if request.method=="POST":
        print(request.POST)  # <QueryDict: {'csrfmiddlewaretoken': ['UlDvceNfBeKeeVdyj8ot6YScOg5MQM7R9kW7pULdq0G7z8D5ZNjuUlYQI4bGh7ku'], 'name': ['123'], 'pwd': ['123'], 'r_pwd': ['123'], 'email': ['123'], 'tel': ['123']}>
        form = UserForm(request.POST)
        if form.is_valid():
            print("form.cleaned_data----", form.cleaned_data)
        else:
            print("form.cleaned_data----", form.cleaned_data)  # {'pwd': '1234', 'email': '123@qq.com', 'tel': '123'}
            print("form.errors----", form.errors)
            print("type(form.errors)----", type(form.errors))  # <class 'django.forms.utils.ErrorDict'>
            print("form.errors.get('name')----", form.errors.get("name"))  # <ul class="errorlist"><li>該字段不能為空</li></ul>
            print("type(form.errors.get('name'))----", type(form.errors.get("name")))  # <class 'django.forms.utils.ErrorList'>
            print("form.errors.get('name')[0]----", form.errors.get("name")[0])
    return render(request, "index.html", locals())

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet"  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh5u" crossorigin="anonymous">
    <script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h4>簡(jiǎn)單form</h4>
        <form action="" method="post" >
            {% csrf_token %}
            <div class="form-group">
                <label for="user_id">用戶名</label>
                <input type="text" id="user_id" class="form-control" name="name">
            </div>
            <div class="form-group">
                <label for="user_id">密碼</label>
                <input type="text" id="user_id" class="form-control" name="pwd">
            </div>
            <div class="form-group">
                <label for="user_id">確認(rèn)密碼</label>
                <input type="text" id="user_id" class="form-control" name="r_pwd">
            </div>
            <div class="form-group">
                <label for="user_id">郵箱</label>
                <input type="text" id="user_id" class="form-control" name="email">
            </div>
            <div class="form-group">
                <label for="user_id">手機(jī)號(hào)</label>
                <input type="text" id="user_id" class="form-control" name="tel">
            </div>
            <input type="submit">

        </form>
    </div>

</div>
</body>
<script type="text/javascript">

</script>
</html>

6.分頁(yè),form組件
6.分頁(yè),form組件

2.2form三種渲染方式

forms.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
from django import forms
from django.forms import widgets

class UserForm(forms.Form):
    # 自定義html中的標(biāo)簽和添加類(lèi)
    name = forms.CharField(min_length=4, label="用戶名", error_messages={"required": "該字段不能為空"},widget=widgets.TextInput(attrs={"class": "form-control"}))
    pwd = forms.CharField(min_length=4, label="密碼", error_messages={"required": "該字段不能為空"},widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    r_pwd = forms.CharField(min_length=4, label="確認(rèn)密碼", error_messages={"required": "該字段不能為空"},widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    email = forms.EmailField(label="郵箱", error_messages={"required": "該字段不能為空", "invalid": "格式錯(cuò)誤"},widget=widgets.EmailInput(attrs={"class": "form-control"}))
    tel = forms.CharField(label="手機(jī)號(hào)", widget=widgets.TextInput(attrs={"class": "form-control"}))

views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage
from app1.models import *
from app1.myforms import *
def index(request):
    form = UserForm()
    if request.method=="POST":
        print(request.POST)  # <QueryDict: {'csrfmiddlewaretoken': ['UlDvceNfBeKeeVdyj8ot6YScOg5MQM7R9kW7pULdq0G7z8D5ZNjuUlYQI4bGh7ku'], 'name': ['123'], 'pwd': ['123'], 'r_pwd': ['123'], 'email': ['123'], 'tel': ['123']}>
        form = UserForm(request.POST)
        if form.is_valid():
            print("form.cleaned_data----", form.cleaned_data)
        else:
            print("form.cleaned_data----", form.cleaned_data)  # {'pwd': '1234', 'email': '123@qq.com', 'tel': '123'}
            print("form.errors----", form.errors)
            print("type(form.errors)----", type(form.errors))  # <class 'django.forms.utils.ErrorDict'>
            print("form.errors.get('name')----", form.errors.get("name"))  # <ul class="errorlist"><li>該字段不能為空</li></ul>
            print("type(form.errors.get('name'))----", type(form.errors.get("name")))  # <class 'django.forms.utils.ErrorList'>
            print("form.errors.get('name')[0]----", form.errors.get("name")[0])
    return render(request, "index.html", locals())

2.2.1渲染方式1

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet"  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh5u" crossorigin="anonymous">
    <script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h4>form組件渲染方式1</h4>
        <form action="" method="post" >
            {% csrf_token %}
            <div class="form-group">
                <label>{{ form.name.label }}</label>
                {{ form.name }} <span class="pull-right error">{{ form.name.errors.0 }}</span>
            </div>
            <div class="form-group">
                <label>{{ form.pwd.label }}</label>
                {{ form.pwd }} <span class="pull-right error">{{ form.pwd.errors.0 }}</span>
            </div>
            <div class="form-group">
                <label>{{ form.r_pwd.label }}</label>
                {{ form.r_pwd }} <span class="pull-right error">{{ form.r_pwd.errors.0 }}</span>
            </div>
            <div class="form-group">
                <label>{{ form.email.label }}</label>
                                <!--錯(cuò)誤信息-->
                {{ form.email }} <span class="pull-right error">{{ form.email.errors.0 }}</span>
            </div>
            <div class="form-group">
                <label for="user_id">手機(jī)號(hào)</label>
                {{ form.tel }} <span class="pull-right error">{{ form.tel.errors.0 }}</span>
            </div>
            <input type="submit">

        </form>
    </div>

</div>
</body>
<script type="text/javascript">

</script>
</html>

6.分頁(yè),form組件
6.分頁(yè),form組件

2.2.2渲染方式2

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet"  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh5u" crossorigin="anonymous">
    <script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h4>form組件渲染方式2</h4>
        <form action="" method="post" >
            {% csrf_token %}
            {% for field in form %}
                <div class="form-group">
                    <label for="">{{ field.label }}</label>
                    {{ field }}
                </div>
            {% endfor %}

            <input type="submit">

        </form>
    </div>

</div>
</body>
<script type="text/javascript">

</script>
</html>

6.分頁(yè),form組件
6.分頁(yè),form組件

2.2.3渲染方式3

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet"  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh5u" crossorigin="anonymous">
    <script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h4>form組件渲染方式3</h4>
        <form action="" method="post" >
            {% csrf_token %}
            {{ form.as_p }}

            <input type="submit">

        </form>
    </div>

</div>
</body>
<script type="text/javascript">

</script>
</html>

6.分頁(yè),form組件
6.分頁(yè),form組件

2.3form組件局部鉤子

# 局部鉤子函數(shù)名為clean_UserForm中字段名
# 返回值為val,報(bào)錯(cuò)時(shí)raise ValidationError("用戶名長(zhǎng)度最長(zhǎng)為12")
# 錯(cuò)誤信息存放在form.errors.get("字段名")[0]
def clean_name(self):
        val = self.cleaned_data.get("name")
        if len(val)<12:
            return val
        else:
            raise ValidationError("用戶名長(zhǎng)度最長(zhǎng)為12")

查看源碼

form.is_valid()

    def is_valid(self):
        """Return True if the form has no errors, or False otherwise."""
        return self.is_bound and not self.errors

        @property
    def errors(self):
        """Return an ErrorDict for the data provided for the form."""
        if self._errors is None:
            self.full_clean()
        return self._errors

    def full_clean(self):
        """
        Clean all of self.data and populate self._errors and self.cleaned_data.
        """
        self._errors = ErrorDict()
        if not self.is_bound:  # Stop further processing.
            return
        self.cleaned_data = {} # 是一個(gè)字典
        # 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():
            return

        self._clean_fields() #局部鉤子所在源碼處,先執(zhí)行局部鉤子函數(shù),然后執(zhí)行全局鉤子函數(shù)
        self._clean_form() #全局鉤子所在源碼處
        self._post_clean()

    def _clean_fields(self):
        for name, field in self.fields.items():
            # 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:
                    value = field.clean(value)
                self.cleaned_data[name] = value #可以看到,驗(yàn)證通過(guò)的字段賦值給了cleaned_data.
                if hasattr(self, 'clean_%s' % name):
                    value = getattr(self, 'clean_%s' % name)()
                    self.cleaned_data[name] = value
            except ValidationError as e:
                self.add_error(name, e)

6.分頁(yè),form組件

2.3.1局部鉤子案例

forms.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
class UserForm(forms.Form):
    # 自定義html中的標(biāo)簽和添加類(lèi)
    name = forms.CharField(min_length=4, label="用戶名", error_messages={"required": "該字段不能為空"},widget=widgets.TextInput(attrs={"class": "form-control"}))
    pwd = forms.CharField(min_length=4, label="密碼", error_messages={"required": "該字段不能為空"},widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    r_pwd = forms.CharField(min_length=4, label="確認(rèn)密碼", error_messages={"required": "該字段不能為空"},widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    email = forms.EmailField(label="郵箱", error_messages={"required": "該字段不能為空", "invalid": "格式錯(cuò)誤"},widget=widgets.EmailInput(attrs={"class": "form-control"}))
    tel = forms.CharField(label="手機(jī)號(hào)", widget=widgets.TextInput(attrs={"class": "form-control"}))

# 局部鉤子函數(shù),必須是clean_字段名
    def clean_tel(self):
        val = self.cleaned_data.get("tel")
        if len(val)==11:
            return val
        else:
            raise ValidationError("手機(jī)格式錯(cuò)誤")

    def clean_name(self):
        val = self.cleaned_data.get("name")
        if len(val)<12:
            return val
        else:
            raise ValidationError("用戶名長(zhǎng)度最長(zhǎng)為12")

views.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage
from app1.models import *
from app1.myforms import *
def index(request):
    form = UserForm()
    if request.method=="POST":
        print(request.POST)  # <QueryDict: {'csrfmiddlewaretoken': ['UlDvceNfBeKeeVdyj8ot6YScOg5MQM7R9kW7pULdq0G7z8D5ZNjuUlYQI4bGh7ku'], 'name': ['123'], 'pwd': ['123'], 'r_pwd': ['123'], 'email': ['123'], 'tel': ['123']}>
        form = UserForm(request.POST)
        if form.is_valid():
            print("form.cleaned_data----", form.cleaned_data)
        else:
            print("form.cleaned_data----", form.cleaned_data)  # {'pwd': '1234', 'email': '123@qq.com', 'tel': '123'}
            print("form.errors----", form.errors)
            print("type(form.errors)----", type(form.errors))  # <class 'django.forms.utils.ErrorDict'>
            print("form.errors.get('name')----", form.errors.get("name"))  # <ul class="errorlist"><li>該字段不能為空</li></ul>
            print("type(form.errors.get('name'))----", type(form.errors.get("name")))  # <class 'django.forms.utils.ErrorList'>
            print("form.errors.get('name')[0]----", form.errors.get("name")[0])
    return render(request, "index.html", locals())

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet"  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh5u" crossorigin="anonymous">
    <script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h4>forms組件渲染方式1</h4>
            <form action="" method="post" novalidate>

                {% csrf_token %}
                <p>{{ form.name.label }}
                    {{ form.name }} <span class="pull-right error">{{ form.name.errors.0 }}</span>
                </p>
                <p>{{ form.pwd.label }}
                    {{ form.pwd }} <span class="pull-right error">{{ form.pwd.errors.0 }}</span>
                </p>
                <p>確認(rèn)密碼
                    {{ form.r_pwd }} <span class="pull-right error">{{ form.r_pwd.errors.0 }}</span><span class="pull-right error">{{ errors.0 }}</span>
                </p>
                <p>郵箱 {{ form.email }} <span class="pull-right error">{{ form.email.errors.0 }}</span></p>
                <p>手機(jī)號(hào) {{ form.tel }} <span class="pull-right error">{{ form.tel.errors.0 }}</span></p>
                <input type="submit">

            </form>
    </div>

</div>
</body>
<script type="text/javascript">

</script>
</html>

6.分頁(yè),form組件
6.分頁(yè),form組件

2.4form組件全局鉤子

    # 全局鉤子,函數(shù)名必須為clean
    # 返回值是self.cleaned_data,報(bào)錯(cuò)時(shí)raise ValidationError("兩次密碼不一致")
    # 錯(cuò)誤信息存放在errors = form.errors.get("__all__").[0]
    def clean(self):
        pwd = self.cleaned_data.get("pwd")
        r_pwd=self.cleaned_data.get("r_pwd")
        # 當(dāng)密碼驗(yàn)證不通過(guò)的時(shí)候,假如密碼pwd為空,就不要驗(yàn)證密碼是否一致了
        if pwd and r_pwd:
            if pwd==r_pwd:
                return self.cleaned_data
            else:
                raise ValidationError("兩次密碼不一致")
        else:
            return self.cleaned_data

全局鉤子源碼

    def _clean_form(self):
        try:
            cleaned_data = self.clean()
        except ValidationError as e:  #這里捕獲ValidationError,所以自己定義的函數(shù)中拋出該異常
            self.add_error(None, e)
        else:
            if cleaned_data is not None:
                self.cleaned_data = cleaned_data

    def clean(self):
        """
        Hook for doing any extra form-wide cleaning after Field.clean() has been
        called on every field. Any ValidationError raised by this method will
        not be associated with a particular field; it will have a special-case
        association with the field named '__all__'.
        """
        return self.cleaned_data   #所以我們重寫(xiě)clean方法,返回值為cleaned_data

6.分頁(yè),form組件

2.4.1全局鉤子案例

forms.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
class UserForm(forms.Form):
    # 自定義html中的標(biāo)簽和添加類(lèi)
    name = forms.CharField(min_length=4, label="用戶名", error_messages={"required": "該字段不能為空"},widget=widgets.TextInput(attrs={"class": "form-control"}))
    pwd = forms.CharField(min_length=4, label="密碼", error_messages={"required": "該字段不能為空"},widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    r_pwd = forms.CharField(min_length=4, label="確認(rèn)密碼", error_messages={"required": "該字段不能為空"},widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    email = forms.EmailField(label="郵箱", error_messages={"required": "該字段不能為空", "invalid": "格式錯(cuò)誤"},widget=widgets.EmailInput(attrs={"class": "form-control"}))
    tel = forms.CharField(label="手機(jī)號(hào)", widget=widgets.TextInput(attrs={"class": "form-control"}))

    def clean_tel(self):
        val = self.cleaned_data.get("tel")
        if len(val)==11:
            return val
        else:
            raise ValidationError("手機(jī)格式錯(cuò)誤")

    def clean_name(self):
        val = self.cleaned_data.get("name")
        if len(val)<12:
            return val
        else:
            raise ValidationError("用戶名長(zhǎng)度最長(zhǎng)為12")

    # 全局鉤子,函數(shù)名必須為clean
    def clean(self):
        pwd = self.cleaned_data.get("pwd")
        r_pwd=self.cleaned_data.get("r_pwd")
        # 當(dāng)密碼驗(yàn)證不通過(guò)的時(shí)候,假如密碼pwd為空,就不要驗(yàn)證密碼是否一致了
        if pwd and r_pwd:
            if pwd==r_pwd:
                return self.cleaned_data
            else:
                raise ValidationError("兩次密碼不一致")
        else:
            return self.cleaned_data

vews.py

from django.shortcuts import render,HttpResponse
from django.core.paginator import Paginator,EmptyPage
from app1.models import *
from app1.myforms import *
def index(request):
    form = UserForm()
    if request.method=="POST":
        print(request.POST)  # <QueryDict: {'csrfmiddlewaretoken': ['UlDvceNfBeKeeVdyj8ot6YScOg5MQM7R9kW7pULdq0G7z8D5ZNjuUlYQI4bGh7ku'], 'name': ['123'], 'pwd': ['123'], 'r_pwd': ['123'], 'email': ['123'], 'tel': ['123']}>
        form = UserForm(request.POST)
        if form.is_valid():
            print("form.cleaned_data----", form.cleaned_data)
        else:
            print("form.cleaned_data----", form.cleaned_data)  # {'pwd': '1234', 'email': '123@qq.com', 'tel': '123'}
            print("form.errors----", form.errors)
            print("type(form.errors)----", type(form.errors))  # <class 'django.forms.utils.ErrorDict'>
            print("form.errors.get('name')----", form.errors.get("name"))  # <ul class="errorlist"><li>該字段不能為空</li></ul>
            print("type(form.errors.get('name'))----", type(form.errors.get("name")))  # <class 'django.forms.utils.ErrorList'>
            print("form.errors.get('name')[0]----", form.errors.get("name")[0])

            errors = form.errors.get("__all__")
            print("errors----", errors)  # <ul class="errorlist nonfield"><li>兩次密碼不一致</li></ul>
            print("type(errors)----", type(errors))  # <class 'django.forms.utils.ErrorList'>
    return render(request, "index.html", locals())

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
    </title>
     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet"  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh5u" crossorigin="anonymous">
    <script type="text/javascript" src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h4>forms組件渲染方式1</h4>
            <form action="" method="post" novalidate>

                {% csrf_token %}
                <p>{{ form.name.label }}
                    {{ form.name }} <span class="pull-right error">{{ form.name.errors.0 }}</span>
                </p>
                <p>{{ form.pwd.label }}
                    {{ form.pwd }} <span class="pull-right error">{{ form.pwd.errors.0 }}</span>
                </p>
                <p>確認(rèn)密碼
                    {{ form.r_pwd }} <span class="pull-right error">{{ form.r_pwd.errors.0 }}</span><span class="pull-right error">{{ errors.0 }}</span>
                </p>
                <p>郵箱 {{ form.email }} <span class="pull-right error">{{ form.email.errors.0 }}</span></p>
                <p>手機(jī)號(hào) {{ form.tel }} <span class="pull-right error">{{ form.tel.errors.0 }}</span></p>
                <input type="submit">

            </form>
    </div>

</div>
</body>
<script type="text/javascript">

</script>
</html>

6.分頁(yè),form組件
6.分頁(yè),form組件

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI