from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request): return HttpResponse('OK') urlpatterns = [ url(r'^index/$', MyView.as_view()), ]
CBV传参,和FBV类似,有名分组,无名分组
url写法:无名分组的
url(r'^cv/(\d{2})/', views.Myd.as_view(),name='cv'),
url(r'^cv/(?P<n>\d{2})/', views.Myd.as_view(name='xxx'),name='cv'),#如果想给类的name属性赋值,前提你的Myd类里面必须有name属性(类属性,定义init方法来接受属性行不通,但是可以自行研究一下,看看如何行通,意义不大),并且之前类里面的name属性的值会被覆盖掉
类写法:
class Myd(View): name = 'sb' def get(self,request,n): print('get方法执行了') print('>>>',n) return render(request,'cvpost.html',{'name':self.name}) def post(self,request,n): print('post方法被执行了') return HttpResponse('post')
添加类的属性可以通过两种方法设置,第一种是常见的Python的方法,可以被子类覆盖。
from django.http import HttpResponse
from django.views import View
class GreetingView(View):
name = "yuan"
def get(self, request):
return HttpResponse(self.name)
# You can override that in a subclass
class MorningGreetingView(GreetingView):
name= "alex"
第二种方法,你也可以在url中指定类的属性:
在url中设置类的属性Python
urlpatterns = [
url(r'^index/$', GreetingView.as_view(name="egon")), #类里面必须有name属性,并且会被传进来的这个属性值给覆盖掉
]