django3-视图函数进阶

1.视图函数的分类

  FBV(fucntion base view)

  CBV(class base view) ,CBV根据定义的方法名 ,判断什么请求执行什么函数

 

2.FBV转换CBV (不太对劲)

  在CBV的url中指定执行类名.as_view()方法 ,根据源码得知dispatch函数中执行了我们自定义的类中方法 !

####################FBV
def
pressedit(request, edit_id, test_id): obj = models.presslist.objects.get(pk=edit_id) print(test_id, edit_id) msg = '' if request.method == 'POST': obj.name = request.POST.get('pressname') if models.presslist.objects.filter(name=obj.name): msg = '已存在' if not obj.name: msg = '不能为空' if not models.presslist.objects.filter(name=obj.name) and obj.name: obj.save() return redirect(reverse('presslist')) return render(request, 'cbsadd-edit.html', {'obj': obj, 'msg': msg}) #######################CBV class pressedit1(View): def get(self, request, edit_id, test_id): obj = models.presslist.objects.get(pk=edit_id) msg = '' print(edit_id, test_id) print(id(obj)) return render(request, 'cbsadd-edit.html', {'obj': obj, 'msg': msg}) def post(self, request, edit_id, test_id): msg = '' obj = models.presslist.objects.get(pk=edit_id) obj.name = request.POST.get('pressname') print(id(obj)) if models.presslist.objects.filter(name=obj.name): msg = '已存在' if not obj.name: msg = '不能为空' if not models.presslist.objects.filter(name=obj.name) and obj.name: obj.save() return redirect(reverse('presslist')) return render(request, 'cbsadd-edit.html', {'obj': obj, 'msg': msg})

 

3.视图函数使用装饰器

import time
import functools
from django.utils.decorators import method_decorator
def wapp(func): @functools.wraps(func) def inner(*args, **kwargs): time1 = time.time() ret = func(*args, **kwargs) print(time.time() - time1) return ret return inner

#######FBV
#url
url(r'^press/edit/(?P\d+)/(?P\d+)/', views.pressedit, name='pressedit'),
#views
@wapp
def presslist(request):
msg_all = models.presslist.objects.all()
return render(request, 'cbs.html', {'msg': msg_all})


#######CBV
#url
url(r'^press/edit/(?P\d+)/(?P\d+)/', views.pressedit1.as_view(), name='pressedit'),

 #views

@method_decorator(wapp, name='get')    ###通过method_decorator这个装饰器指定自己的装饰器 和要装饰的函数 ,可以直接作用dispatch函数,对所有函数生效
class pressedit1(View):

def get(self, request, edit_id, test_id, msg=''):
obj = models.presslist.objects.get(pk=edit_id)
return render(request, 'cbsadd-edit.html', {'obj': obj, 'msg': msg})

def post(self, request, edit_id, test_id):
msg = ''
obj = models.presslist.objects.get(pk=edit_id)
obj.name = request.POST.get('pressname')
if models.presslist.objects.filter(name=obj.name):
msg = '已存在'
if not obj.name:
msg = '不能为空'
if not models.presslist.objects.filter(name=obj.name) and obj.name:
obj.save()
return redirect(reverse('presslist'))
return self.get(request, edit_id, test_id, msg)

 

你可能感兴趣的:(django3-视图函数进阶)