1、CBV模式和FBV模式html
FBV模式(function base views):就是在視圖裏使用函數處理請求前端
CBV模式(class base views) 就是在視圖裏使用類處理請求python
CBV模式的優勢主要下面兩種:git
提升了代碼的複用性,能夠使用面嚮對象的技術,好比Mixin(多繼承)django
能夠用不一樣的函數針對不一樣的HTTP方法處理,而不是經過不少if判斷,提升代碼可讀性小程序
urls.py文件:app
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', views.LoginView.as_view()), # view()===self.dispatch()===self.get() ]
views.py文件:ide
from django.shortcuts import render, HttpResponse from django.views import View class LoginView(View): def dispatch(self, request, *args, **kwargs): ret=super().dispatch(request, *args, **kwargs) #super():python3中繼承父類的方法,不然會覆蓋父類的方法 return ret def get(self,request): return render(request, "login.html") def post(self,request): user=request.POST.get("user") return HttpResponse(user) #視圖類定義各類方法,代替了在視圖函數的if請求方式判斷, # 若是沒有自定義dispatch方法,就執行父類的dispatch方法,而後執行對應的get或post方法, #若是有自定義dispatch方法,就執行自定義的dispatch方法,可是自定義的dispatch方法必須繼承父類的方法
2、ModelForm函數
ModelForm用起來是很是方便的,好比增長修改之類的操做。可是也帶來額外很差的地方,model和form之間耦合了。若是不耦合的話,mf.save()方法也沒法直接提交保存。 可是耦合的話使用場景一般侷限用於小程序,寫大程序就最好不用了。post
一、建立modelform
from django.forms import ModelForm #在視圖函數中,定義一個類,好比就叫StudentList,這個類要繼承ModelForm,在這個類中再寫一個原類Meta(規定寫法,並注意首字母是大寫的) #在這個原類中,有如下屬性(部分): class StudentList(ModelForm): class Meta: model =Student #對應的Model中的類 fields = "__all__" #字段,若是是__all__,就是表示列出全部的字段 exclude = None #排除的字段 #error_messages用法: error_messages = { 'name':{'required':"用戶名不能爲空",}, 'age':{'required':"年齡不能爲空",}, } #widgets用法,好比把輸入用戶名的input框給爲Textarea #首先得導入模塊 from django.forms import widgets as wid #由於重名,因此起個別名 widgets = { "name":wid.Textarea(attrs={"class":"c1"}) #還能夠自定義屬性 } #labels,自定義在前端顯示的名字 labels= { "name":"用戶名" }
二、視圖函數
views.py文件:
from django.shortcuts import render,HttpResponse,redirect from django.forms import ModelForm from app01 import models def test(request): # model_form = models.Student model_form = models.Student.objects.all() return render(request,'test.html',{'model_form':model_form}) class StudentList(ModelForm): class Meta: model = models.Student #對應的Model中的類 fields = "__all__" #字段,若是是__all__,就是表示列出全部的字段 exclude = None #排除的字段 labels = None #提示信息 help_texts = None #幫助提示信息 widgets = None #自定義插件 error_messages = None #自定義錯誤信息 #error_messages用法: error_messages = { 'name':{'required':"用戶名不能爲空",}, 'age':{'required':"年齡不能爲空",}, } #widgets用法,好比把輸入用戶名的input框給爲Textarea #首先得導入模塊 from django.forms import widgets as wid #由於重名,因此起個別名 widgets = { "name":wid.Textarea } #labels,自定義在前端顯示的名字 labels= { "name":"用戶名" } def student(request): if request.method == 'GET': student_list = StudentList() return render(request,'student.html',{'student_list':student_list}) else: student_list = StudentList(request.POST) if student_list.is_valid(): student_list.save() return render(request,'student.html',{'student_list':student_list}) def student_edit(request,pk): obj = models.Student.objects.filter(pk=pk).first() if not obj: return redirect('test') if request.method == "GET": student_list = StudentList(instance=obj) return render(request,'student_edit.html',{'student_list':student_list}) else: student_list = StudentList(request.POST,instance=obj) if student_list.is_valid(): student_list.save() return render(request,'student_edit.html',{'student_list':student_list})
三、student.html頁面
<body> <div class="container"> <h1>student</h1> <form method="POST" novalidate> {% csrf_token %} {# {{ student_list.as_p }}#} {#能夠用as_p顯示所有#} {% for student in student_list %} <div class="form-group col-md-6"> {# 拿到數據字段的verbose_name,沒有就默認顯示字段名 #} <label class="col-md-3 control-label">{{ student.label }}</label> <div class="col-md-9" style="position: relative;">{{ student }}</div> </div> {% endfor %} <div class="col-md-2 col-md-offset-10"> <input type="submit" value="提交" class="btn-primary"> </div> </form> </div> </body> 如今還缺一個input框的form-contral樣式,能夠考慮在後臺的widget裏面添加 好比這樣: from django.forms import widgets as wid #由於重名,因此起個別名 widgets = { "name":wid.TextInput(attrs={'class':'form-control'}), "age":wid.NumberInput(attrs={'class':'form-control'}), "email":wid.EmailInput(attrs={'class':'form-control'}) }
四、基於form組件和model form組件的對比
models.py文件:
from django.db import models class Author(models.Model): nid = models.AutoField(primary_key=True) name=models.CharField( max_length=32) age=models.IntegerField() authorDetail=models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE) def __str__(self): return self.name class AuthorDetail(models.Model): nid = models.AutoField(primary_key=True) birthday=models.DateField() telephone=models.BigIntegerField() addr=models.CharField( max_length=64) class Publish(models.Model): nid = models.AutoField(primary_key=True) name=models.CharField( max_length=32) city=models.CharField( max_length=32) email=models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField( max_length=32) publishDate=models.DateField() price=models.DecimalField(max_digits=5,decimal_places=2) publish=models.ForeignKey(to="Publish",to_field="nid",on_delete=models.CASCADE) authors=models.ManyToManyField(to='Author',) # 與Author表創建多對多的關係,ManyToManyField能夠建在兩個模型中的任意一個,自動建立第三張表
#執行下面python語句生成相關表(數據遷移)
python3 manage.py makemigrations python3 manage.py migrate
urls.py文件:
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^add_book/', views.AddBookView.as_view()), url(r'^edit_book/(\d+)', views.EditBookView.as_view()), ]
views.py文件:
from django.shortcuts import render,HttpResponse from django.views import View from django import forms from .models import Publish,Author,Book #########################################################以前學習的基於form組件######################################################### class BookForm(forms.Form): title=forms.CharField() price=forms.DecimalField() publishDate=forms.DateField() #state=forms.ChoiceField(choices=[(1,"已出版"),(2,"未出版")]) publish=forms.ModelChoiceField(queryset=Publish.objects.all()) authors=forms.ModelMultipleChoiceField(queryset=Author.objects.all()) #########################################################基於model form組件######################################################### from django.forms import ModelForm class BookModelForm(ModelForm): class Meta: model=Book ##對應的Model中的Book類 fields="__all__" class AddBookView(View): def get(self,request): form=BookModelForm() return render(request,"addbook.html",locals()) def post(self,request): form=BookModelForm(request.POST) if form.is_valid(): # print("cleaned_data:",form.cleaned_data) # form.cleaned_data.pop("authors") # Book.objects.create(**form.cleaned_data) #基於form實現的添加記錄 form.save() #基於model form,會自動添加記錄 return HttpResponse("OK") else: print(form.cleaned_data) print(form.errors) return HttpResponse("OK") class EditBookView(View): def get(self,request,id): edit_book=Book.objects.get(pk=id) form = BookModelForm(instance=edit_book) #編輯的時候須要一個instance,讓instance=一個你要編輯的那個對象 return render(request,"editbook.html",locals()) def post(self,request,id): edit_book = Book.objects.get(pk=id) form=BookModelForm(request.POST,instance=edit_book) if form.is_valid(): form.save() return HttpResponse("OK") else: print(form.cleaned_data) print(form.errors) return HttpResponse("OK")html頁面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" novalidate method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> </body> </html>