Django从理论到实战(part46)--View类
學(xué)習(xí)筆記,僅供參考,有錯(cuò)必糾
參考自:Django打造大型企業(yè)官網(wǎng)–Huang Y;
類視圖
View類
django.views.generic.base.View是主要的類視圖,所有的類視圖都是繼承自他,我們寫(xiě)自己的類視圖,也可以繼承自他。
如果該視圖只能使用get的方式來(lái)請(qǐng)求,那么就可以在這個(gè)類中定義get(self,request,*args,**kwargs)方法;如果只需要實(shí)現(xiàn)post方法,那么就只需要在類中實(shí)現(xiàn)post(self,request,*args,**kwargs)。
- 舉個(gè)例子(擁有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ā)起請(qǐng)求,填寫(xiě)form表單:
點(diǎn)擊提交:
- 舉個(gè)例子(定義http_method_not_allowed方法)
如果在上面的例子中,我們只有g(shù)et方法,沒(méi)有post方法,但是,我們卻進(jìn)行了post操作,那么Django會(huì)把這個(gè)請(qǐng)求轉(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請(qǐng)求!" % request.method)向http://127.0.0.1:8000/add_book2/發(fā)起請(qǐng)求,填寫(xiě)form表單:
點(diǎn)擊提交:
總結(jié)
以上是生活随笔為你收集整理的Django从理论到实战(part46)--View类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Django从理论到实战(part45)
- 下一篇: Django从理论到实战(part47)