4👍
You can use a decorator for applying a logic to a view with possible redirect(if you can really put your logic outside the view).
def check_my_logic(view):
def wrap(request, *args, **kwargs):
# do some logic here
if all_ok:
return view(request, *args, **kwargs)
else:
return HttpResponse(status=403)
return wrap
and then in views.py:
from mydecorators import check_my_logic
@check_my_logic
def some_view(request):
....
5👍
Your mistake is, in myView
function, you call your checkFunction
, but you do not use the return value of checkFunction
so your return value of checkFunction
return HttpResponse(status=403)
got lost and never returned within myView
.
It might be like:
def myView(request):
result = checkFunction()
if result:
return result
#if no problem, keep running on...
def checkFunction():
#do stuff
if something_goes_wrong:
return HttpResponse(status=403)
# you do not need to return anything if no error occured...
So, if nothing goes wrong, then checkFunction
will not return anything, and result
will be None
and if result:
block will not be executed. If you return a response, than your view will return that response (in your situation, HttpResponse(status=403)
)…
UPDATE: Then you can do this….
def checkFunction(request):
#do stuff
if something_goes_wrong:
return HttpResponse(status=403)
elif some_other_issue:
return HttpResponse(....)
else: #no problems, everything is as expected...
return render_to_response(...) # or any kind of response you want
def myView(request):
return checkFunction(request)
this way, your view will return what your checkFunction
returns…
Also, passing request
object to your checkFunction
might be necessary since you wish to creeate your response there. You might need it.