亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

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

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

6.分頁,form組件

發布時間:2020-07-06 19:55:48 來源:網絡 閱讀:447 作者:DevOperater 欄目:編程語言

1.分頁功能

1.1批量插入數據

# 批量插入數據
    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)  # 每頁顯示10條數據
    print(paginator.count)  # 總數據數  105
    print(paginator.num_pages)  # 總頁數  11
    print(paginator.page_range)  # 頁碼的列表  range(1, 12)
    page1 = paginator.page(1)  # 第一頁的book對象列表
    print(page1)  # <Page 1 of 11>
    for i in page1:  # 遍歷第一頁的所有數據對象
        print(i)  # Book object (16)
    print(page1.object_list)  # 第一頁的所有數據[<Book: Book object (7)>, ... <Book: Book object (16)>]

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

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

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

1.3分頁案例

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)  # 每頁顯示7條數據
    current_page = int(request.GET.get("page", 1))  # 沒有page這個key,就設置為1

# 這里是保證當前最多只顯示11個頁碼
    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

    # 顯示當前頁的book對象列表
    try:
        current_page_contents = paginator.page(current_page)
    #     如果數據為空,顯示第一頁的數據
    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">

{#    當前頁有上一頁的時候,才可點擊#}
        {% if current_page_contents.has_previous %}
            <li><a href="?page={{ current_page_contents.previous_page_number }}" aria-label="Previous">
            <span aria-hidden="true">上一頁</span>
            </a></li>
        {% else %}
            <li class="disabled"><a href="" aria-label="Previous" >
            <span aria-hidden="true">上一頁</span>
            </a></li>
        {% endif %}

      {% for page_num in page_range %}
{#          前面的內容就是當前訪問的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">下一頁</span>
            </a></li>
        {% else %}
            <li class="disabled"><a href="" aria-label="Next">
                <span aria-hidden="true">下一頁</span>
            </a></li>
        {% endif %}

  </ul>
</nav>

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

</script>
</html>

6.分頁,form組件
6.分頁,form組件
6.分頁,form組件

2.forms組件

作用:
主要是校驗字段功能

2.1簡單form

注意:
1.即使不是所有字段驗證通過,form.cleaned_data中也有通過驗證的字段的值。
2.前端傳過來的字段可以比UserForm中的字段多,多余的字段不進行驗證。所有字段驗證通過,form.is_valid()返回true。
3.前端傳過來的字段比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="確認密碼", error_messages={"required": "該字段不能為空"})
    email = forms.EmailField(label="郵箱" , error_messages={"required": "該字段不能為空", "invalid": "格式錯誤"})
    tel = forms.CharField(label="手機號")

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>簡單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">確認密碼</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">手機號</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.分頁,form組件
6.分頁,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中的標簽和添加類
    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="確認密碼", error_messages={"required": "該字段不能為空"},widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    email = forms.EmailField(label="郵箱", error_messages={"required": "該字段不能為空", "invalid": "格式錯誤"},widget=widgets.EmailInput(attrs={"class": "form-control"}))
    tel = forms.CharField(label="手機號", 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>
                                <!--錯誤信息-->
                {{ form.email }} <span class="pull-right error">{{ form.email.errors.0 }}</span>
            </div>
            <div class="form-group">
                <label for="user_id">手機號</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.分頁,form組件
6.分頁,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.分頁,form組件
6.分頁,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.分頁,form組件
6.分頁,form組件

2.3form組件局部鉤子

# 局部鉤子函數名為clean_UserForm中字段名
# 返回值為val,報錯時raise ValidationError("用戶名長度最長為12")
# 錯誤信息存放在form.errors.get("字段名")[0]
def clean_name(self):
        val = self.cleaned_data.get("name")
        if len(val)<12:
            return val
        else:
            raise ValidationError("用戶名長度最長為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 = {} # 是一個字典
        # 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() #局部鉤子所在源碼處,先執行局部鉤子函數,然后執行全局鉤子函數
        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 #可以看到,驗證通過的字段賦值給了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.分頁,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中的標簽和添加類
    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="確認密碼", error_messages={"required": "該字段不能為空"},widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    email = forms.EmailField(label="郵箱", error_messages={"required": "該字段不能為空", "invalid": "格式錯誤"},widget=widgets.EmailInput(attrs={"class": "form-control"}))
    tel = forms.CharField(label="手機號", widget=widgets.TextInput(attrs={"class": "form-control"}))

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

    def clean_name(self):
        val = self.cleaned_data.get("name")
        if len(val)<12:
            return val
        else:
            raise ValidationError("用戶名長度最長為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>確認密碼
                    {{ 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>手機號 {{ 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.分頁,form組件
6.分頁,form組件

2.4form組件全局鉤子

    # 全局鉤子,函數名必須為clean
    # 返回值是self.cleaned_data,報錯時raise ValidationError("兩次密碼不一致")
    # 錯誤信息存放在errors = form.errors.get("__all__").[0]
    def clean(self):
        pwd = self.cleaned_data.get("pwd")
        r_pwd=self.cleaned_data.get("r_pwd")
        # 當密碼驗證不通過的時候,假如密碼pwd為空,就不要驗證密碼是否一致了
        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,所以自己定義的函數中拋出該異常
            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   #所以我們重寫clean方法,返回值為cleaned_data

6.分頁,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中的標簽和添加類
    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="確認密碼", error_messages={"required": "該字段不能為空"},widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    email = forms.EmailField(label="郵箱", error_messages={"required": "該字段不能為空", "invalid": "格式錯誤"},widget=widgets.EmailInput(attrs={"class": "form-control"}))
    tel = forms.CharField(label="手機號", 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("手機格式錯誤")

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

    # 全局鉤子,函數名必須為clean
    def clean(self):
        pwd = self.cleaned_data.get("pwd")
        r_pwd=self.cleaned_data.get("r_pwd")
        # 當密碼驗證不通過的時候,假如密碼pwd為空,就不要驗證密碼是否一致了
        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>確認密碼
                    {{ 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>手機號 {{ 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.分頁,form組件
6.分頁,form組件

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

兰坪| 潞城市| 灵宝市| 沈阳市| 溧阳市| 建始县| 罗山县| 长沙县| 永和县| 景泰县| 温宿县| 罗田县| 门源| 河北省| 江达县| 延津县| 蚌埠市| 班戈县| 北票市| 那曲县| 哈密市| 泰顺县| 南部县| 沧源| 蓝田县| 同江市| 余江县| 延安市| 泌阳县| 谷城县| 南澳县| 黎川县| 林口县| 尚义县| 泽普县| 和平县| 勃利县| 陇南市| 崇仁县| 滦南县| 浮梁县|