我为我的django app写了两个非常简单的装饰器:
def login_required_json(f):
def inner(request, *args, **kwargs):
#this check the session if userid key exist, if not it will redirect to login page
if not request.user.is_authenticated():
result=dict()
result["success"]=False
result["message"]="The user is not authenticated"
return HttpResponse(content=simplejson.dumps(result),mimetype="application/json")
else:
return f(request, *args, **kwargs)
def catch_404_json(f):
def inner(*args,**kwargs):
try:
return f(*args, **kwargs)
except Http404:
result=dict()
result["success"]=False
result["message"]="The some of the resources throw 404"
return HttpResponse(content=simplejson.dumps(result),mimetype="application/json")
但是当我将它们应用到我的视图中时,模板中出现“ViewDoesNotExist”错误,说它无法导入视图,因为它不可调用。我做错了什么?
答案 0 :(得分:3)
def login_required_json(f):
def inner(request, *args, **kwargs):
#this check the session if userid key exist, if not it will redirect to login page
if not request.user.is_authenticated():
result=dict()
result["success"]=False
result["message"]="The user is not authenticated"
return HttpResponse(content=simplejson.dumps(result),mimetype="application/json")
else:
return f(request, *args, **kwargs)
return inner # <--- Here
您的装饰器返回None,而不是实际视图。 因此,如上所述,返回内部函数。