Django从理论到实战(part46)--View类
生活随笔
收集整理的這篇文章主要介紹了
Django从理论到实战(part46)--View类
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
學(xué)習(xí)筆記,僅供參考,有錯必糾
參考自:Django打造大型企業(yè)官網(wǎng)–Huang Y;
類視圖
View類
django.views.generic.base.View是主要的類視圖,所有的類視圖都是繼承自他,我們寫自己的類視圖,也可以繼承自他。
如果該視圖只能使用get的方式來請求,那么就可以在這個類中定義get(self,request,*args,**kwargs)方法;如果只需要實現(xiàn)post方法,那么就只需要在類中實現(xiàn)post(self,request,*args,**kwargs)。
- 舉個例子(擁有g(shù)et和post方法)
首先,我們定義視圖類AddBookView:
class AddBookView(View):def get(self, request, *args, **kwargs):return render(request, "add_book.html")def post(self, request, *args, **kwargs):book = request.POST.get("book", "")price = request.POST.get("price", "")tags = request.POST.getlist("tags")context = {"book":book,"price":price,"tags":tags}return render(request, "show_books.html", context = context)再定義主urls.py文件:
from django.contrib import admin from django.urls import path from . import views from django.conf.urls import includeurlpatterns = [path('admin/', admin.site.urls),path("add_book2/", views.AddBookView.as_view(), name = "add_book2"), ]向http://127.0.0.1:8000/add_book2/發(fā)起請求,填寫form表單:
點擊提交:
- 舉個例子(定義http_method_not_allowed方法)
如果在上面的例子中,我們只有g(shù)et方法,沒有post方法,但是,我們卻進(jìn)行了post操作,那么Django會把這個請求轉(zhuǎn)發(fā)給http_method_not_allowed方法:
class AddBookView(View):def get(self, request, *args, **kwargs):return render(request, "add_book.html")def http_method_not_allowed(self, request, *args, **kwargs):return HttpResponse("您當(dāng)前采用的method是:%s,本視圖只支持使用get請求!" % request.method)向http://127.0.0.1:8000/add_book2/發(fā)起請求,填寫form表單:
點擊提交:
總結(jié)
以上是生活随笔為你收集整理的Django从理论到实战(part46)--View类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Django从理论到实战(part45)
- 下一篇: 安徽的蒿子粑粑怎么做