1. 程式人生 > >CBV模式和model form組件

CBV模式和model form組件

CBV model form組件

一、CBV模式和FBV模式

FBV模式(function base views):就是在視圖裏使用函數處理請求

CBV模式(class base views) 就是在視圖裏使用類處理請求


CBV模式的優點主要下面兩種:

提高了代碼的復用性,可以使用面向對象的技術,比如Mixin(多繼承)

可以用不同的函數針對不同的HTTP方法處理,而不是通過很多if判斷,提高代碼可讀性


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'^login/', views.LoginView.as_view()),          # view()===self.dispatch()===self.get()
]

views.py文件:

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方法必須繼承父類的方法

二、ModelForm

ModelForm用起來是非常方便的,比如增加修改之類的操作。但是也帶來額外不好的地方,model和form之間耦合了。如果不耦合的話,mf.save()方法也無法直接提交保存。 但是耦合的話使用場景通常局限用於小程序,寫大程序就最好不用了。

1、創建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":"用戶名"
        }

2、視圖函數

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})

3、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'})
}

4、基於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>




CBV模式和model form組件