django中FBC和CBV模式的urls和views的对应写法

FBV

urls:

urlpatterns = [

  url(r'^admin/', admin.site.urls),
  url(r'^home/', views.home),
]

views:

def home(request):
   return render(request, 'home.html')

 

CBV

urls:

urlpatterns = [

   url(r'^admin/', admin.site.urls),
 url(r'^home/', views.Home.as_view()), #固定写法 
]

views:

from django.views import View
class Home(View):

  def get(self,request):
    print(request.method)
    return render(request, 'home.html')

  def post(self,request):
    print(request.method,'POST')
    return render(request, 'home.html')

 

方式二:

  

from django.views import View
class Home(View):

  def dispatch(self, request, *args, **kwargs):   #反射调用 类中的方法     其实和上面的写法一样
    # 调用父类中的dispatch
    print('before')
    result = super(Home,self).dispatch(request, *args, **kwargs)
    print('after')
    return result

  def get(self,request):
    print(request.method)
    return render(request, 'home.html')

  def post(self,request):
    print(request.method,'POST')
    return render(request, 'home.html')

 

posted @ 2019-05-05 14:10  Samuel-Leung  阅读(406)  评论(0编辑  收藏  举报