from django import forms from app01 import models class BookModelForm(forms.ModelForm): class Meta: # 告訴Django這個form類和那個model類對應 model = models.Book # 告訴Django這個form類裏面有哪些字段 fields = "__all__" widgets = { "publish_date": forms.widgets.DateInput( # 給日期字段添加日期類型 attrs={"type": "date"} ) } labels = { "title": "書名", "price": "價格", "publish_date": '出版日期', "publisher": "出版社名稱", "authors": "做者" } error_messages = { "title": { "required": "書名不能爲空" } } # 經過修改類的初始化方法達到批量添加共同屬性的目的 def __init__(self, *args, **kwargs): super(BookModelForm, self).__init__(*args, **kwargs) # for field_name in self.base_fields: for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' })
##2. ModelForm全部屬性:css
class Meta: model, # 對應Model的 fields=None, # 字段 exclude=None, # 排除字段 labels=None, # 提示信息 help_texts=None, # 幫助提示信息 widgets=None, # 自定義插件 error_messages=None, # 自定義錯誤信息(總體錯誤信息from django.core.exceptions import NON_FIELD_ERRORS) field_classes=None # 自定義字段類 (也能夠自定義字段) localized_fields=('birth_date',) # 本地化,如:根據不一樣時區顯示數據
##3. ModelForm用於驗證用戶數據:is_valid()html
model_form_obj = XXOOModelForm() //實例化對象 model_form_obj.is_valid() // 校驗數據 model_form_obj.errors.as_json() //錯誤 model_form_obj.clean() //同Form組件中的屬性 model_form_obj.cleaned_data // 同Form組件中的屬性
##4. ModelForm用於建立數據:save()前端
def add_book(request): if request.method == "POST": #直接傳request.POST,進行ModelForm的實例化傳參 form_obj = forms.BookModelForm(request.POST) if form_obj.is_valid(): # 校驗數據 form_obj.save() #直接就能夠保存數據到數據庫,包括多對多,多對一,一對一的關係 return redirect("/book_list/") #ModelForm實例化對象 form_obj = forms.BookModelForm() return render(request, "v2/add_book.html", locals())
##5. ModelForm用於初始化:ModelForm(instance=model_obj)python
def edit_book(request, pk): book_obj = models.Book.objects.filter(id=pk).first() #form_obj經過initial設置初始化的值,例如,圖書管理系統中的編輯書籍功能, #點擊編輯後跳轉到編輯書籍頁面,跳轉後須要用要編輯的書籍信息填充頁面對應信息。 #不一樣於Form組件的是,ModelForm直接就能夠傳實例化的對象,而不須要將對象轉化成字典的形式傳。 form_obj = forms.BookModelForm(instance=book_obj) return render(request, "v2/edit_book.html", locals())
##6. ModelForm用於更新 :ModelForm(request.POST, instance=book_obj)git
def edit_book(request, pk): book_obj = models.Book.objects.filter(id=pk).first() if request.method == "POST": #修改數據時,直接能夠將用戶數據包request.POST傳進去, #再傳一個要修改的對象的示例,ModelForm就能夠自動完成修改數據了。 form_obj = forms.BookModelForm(request.POST, instance=book_obj) if form_obj.is_valid(): // 數據校驗 form_obj.save() // 直接保存 return redirect("/book_list/") #form_obj經過initial設置初始化的值,例如,圖書管理系統中的編輯書籍功能, #點擊編輯後跳轉到編輯書籍頁面,跳轉後須要用要編輯的書籍信息填充頁面對應信息。 #不一樣於Form組件的是,ModelForm直接就能夠傳實例化的對象,而不須要將對象轉化成字典的形式傳。 form_obj = forms.BookModelForm(instance=book_obj) return render(request, "v2/edit_book.html", locals())
##8. 經過ModelForm實現的書籍、做者、出版社的管理代碼示例:數據庫
from django.db import models class Publisher(models.Model): name = models.CharField(max_length=12) address = models.TextField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=12) gender = models.SmallIntegerField( choices=((0, '女'), (1, '男'), (2, '保密')) ) age = models.IntegerField() def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) # 0~999.99 publish_date = models.DateField() publisher = models.ForeignKey(to="Publisher", on_delete=models.CASCADE) authors = models.ManyToManyField(to="Author") def __str__(self): return self.title
from django import forms from app01 import models class BookModelForm(forms.ModelForm): class Meta: # 告訴Django這個form類和那個model類對應 model = models.Book # 告訴Django這個form類裏面有哪些字段 fields = "__all__" widgets = { "publish_date": forms.widgets.DateInput( # 給日期字段添加日期類型 attrs={"type": "date"} ) } labels = { "title": "書名", "price": "價格", "publish_date": '出版日期', "publisher": "出版社名稱", "authors": "做者" } error_messages = { "title": { "required": "書名不能爲空" } } # 經過修改類的初始化方法達到批量添加共同屬性的目的 def __init__(self, *args, **kwargs): super(BookModelForm, self).__init__(*args, **kwargs) # for field_name in self.base_fields: for field_name in iter(self.fields): field = self.base_fields[field_name] field.widget.attrs.update({ "class": "form-control", })
from django.shortcuts import render,redirect from app01 import modelform from app01 import models def book_list(request): book_list = models.Book.objects.all() return render(request, 'book_list.html', {'book_list': book_list}) def add_book(request): if request.method == "POST": # modelform 直接能夠將從前端拿到的數據組request.POST #當參數傳給實例化的Modelform form_obj = modelform.BookModelForm(request.POST) # 調用is_valid()方法校驗數據 if form_obj.is_valid(): # 直接保存到數據庫中 form_obj.save() return redirect("/book_list/") modelform_obj = modelform.BookModelForm() return render(request, 'add_book.html', {"modelform_obj": modelform_obj}) def edit_book(request,pk): book_obj = models.Book.objects.filter(id=pk).first() if request.method == "POST": #修改數據時,直接能夠將用戶數據包request.POST傳進去, #再傳一個要修改的對象的示例,ModelForm就能夠自動完成修改數據了。 form_obj = modelform.BookModelForm(request.POST, instance=book_obj) if form_obj.is_valid(): form_obj.save() return redirect("/book_list/") # form_obj經過initial設置初始化的值,例如,圖書管理系統中的編輯書籍功能, # 點擊編輯後跳轉到編輯書籍頁面,跳轉後須要用要編輯的書籍信息填充頁面對應信息。 # 不一樣於Form組件的是,ModelForm直接就能夠傳實例化的對象,而不須要將對象轉化成字典的形式傳。 form_obj = modelform.BookModelForm(instance=book_obj) #locals()是將本地數據鍵值對的簡寫形式 return render(request, "edit_book.html", locals())
<!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 href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"> <title>查看書籍</title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="alert alert-success text-center" role="alert"> <h1 class="text-center">圖書管理系統</h1> </div> <div class="panel panel-default panel-primary"> <div class="panel-heading ">查看書籍</div> <div class="panel-body"> <table class=" table table-striped"> <thead> <tr> <td>編號</td> <td>書名</td> <td>出版時間</td> <td>價格</td> <td>出版社</td> <td>做者</td> <td>操做</td> </tr> </thead> {% for book in book_obj %} <tbody> <tr> <td>{{ forloop.counter }}</td> <td>{{ book.title }}</td> <td>{{ book.publishDate|date:"Y-m-d" }}</td> <td>{{ book.price}}</td> <td>{{ book.publishes.name }}</td> <td>{{ book.author_name }}</td> <td> <a href="{% url 'edit' book.pk %}" class="btn btn-danger">編輯</a> <a href="{% url 'delete' book.pk %}" class="btn btn-warning">刪除</a> </td> </tr> </tbody> {% endfor %} </table> <a href="{% url 'add' %}" class="btn btn-success pull-right">添加書籍</a> </div> </div> </div> </div> </div> </body> </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"> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"> <title>Title</title> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form action="" method="post"> {% csrf_token %} {% for field in new_book %} <div class="form-group"> {{ field.label }} {{ field }} </div> {% endfor %} <button type="submit" class="btn btn-success pull-right">保存</button> </form> </div> </div> </div> </body> </html>
{% extends "add_book.html" %}
##10. ModelForm進階(同Form組件)django
# 經過修改類的初始化方法達到批量添加共同屬性的目的 def __init__(self, *args, **kwargs): super(BookModelForm, self).__init__(*args, **kwargs) # for field_name {in self.base_fields: for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' })