# 批量插入數(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)
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
book_list = Book.objects.all()
paginator = Paginator(book_list, 10) # 每頁顯示10條數(shù)據(jù)
print(paginator.count) # 總數(shù)據(jù)數(shù) 105
print(paginator.num_pages) # 總頁數(shù) 11
print(paginator.page_range) # 頁碼的列表 range(1, 12)
page1 = paginator.page(1) # 第一頁的book對象列表
print(page1) #
for i in page1: # 遍歷第一頁的所有數(shù)據(jù)對象
print(i) # Book object (16)
print(page1.object_list) # 第一頁的所有數(shù)據(jù)[, ... ]
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
views.py
成都創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站建設、網(wǎng)站制作與策劃設計,賓縣網(wǎng)站建設哪家好?成都創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設10年,網(wǎng)設計領(lǐng)域的專業(yè)建站公司;建站業(yè)務涵蓋:賓縣等地區(qū)。賓縣做網(wǎng)站價格咨詢:028-86922220
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條數(shù)據(jù)
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)
# 如果數(shù)據(jù)為空,顯示第一頁的數(shù)據(jù)
except EmptyPage as e:
current_page_contents = paginator.page(1)
return render(request, "index.html",locals())
index.html
{% for book_obj in current_page_contents %}
- {{ book_obj.title }}--{{ book_obj.price }}
{% endfor %}
作用:
主要是校驗字段功能
注意:
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) #
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)) #
print("form.errors.get('name')----", form.errors.get("name")) # - 該字段不能為空
print("type(form.errors.get('name'))----", type(form.errors.get("name"))) #
print("form.errors.get('name')[0]----", form.errors.get("name")[0])
return render(request, "index.html", locals())
index.html
簡單form
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) #
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)) #
print("form.errors.get('name')----", form.errors.get("name")) # - 該字段不能為空
print("type(form.errors.get('name'))----", type(form.errors.get("name"))) #
print("form.errors.get('name')[0]----", form.errors.get("name")[0])
return render(request, "index.html", locals())
index.html
form組件渲染方式1
index.html
form組件渲染方式2
index.html
form組件渲染方式3
# 局部鉤子函數(shù)名為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() #局部鉤子所在源碼處,先執(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 #可以看到,驗證通過的字段賦值給了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)
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"}))
# 局部鉤子函數(shù),必須是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) #
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)) #
print("form.errors.get('name')----", form.errors.get("name")) # - 該字段不能為空
print("type(form.errors.get('name'))----", type(form.errors.get("name"))) #
print("form.errors.get('name')[0]----", form.errors.get("name")[0])
return render(request, "index.html", locals())
index.html
forms組件渲染方式1
# 全局鉤子,函數(shù)名必須為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,所以自己定義的函數(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 #所以我們重寫clean方法,返回值為cleaned_data
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")
# 全局鉤子,函數(shù)名必須為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) #
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)) #
print("form.errors.get('name')----", form.errors.get("name")) # - 該字段不能為空
print("type(form.errors.get('name'))----", type(form.errors.get("name"))) #
print("form.errors.get('name')[0]----", form.errors.get("name")[0])
errors = form.errors.get("__all__")
print("errors----", errors) # - 兩次密碼不一致
print("type(errors)----", type(errors)) #
return render(request, "index.html", locals())
index.html
forms組件渲染方式1