问题
I'm excepting this code at is_send_permitted_interceptor if true to stop processing and redirect to forbidden. However, it does not, instead it returns the HttpResponseForbidden object in the function.
How do I actually get HttpResponseForbidden() to run in this context.
@login_required
def process_all(request):
#If we had a POST then get the request post values.
if request.method == 'POST':
batches = Batch.objects.for_user_pending(request.user)
# Will redirect/cancel request if user does not meet requirements, funds, permissions etc
is_send_permitted_interceptor(request)
# stuff here if everything is ok
def is_send_permitted_interceptor(request):
# Check user has required credits in account to these batches.
balance = Account.objects.get(user=request.user).get_balance()
cost_of_sending = Batch.objects.batches_cost_pending(user=request.user)
if balance < cost_of_sending:
return HttpResponseForbidden()
else:
pass
回答1:
You don't return the output of the "interceptor" in the process_all
view, so it never reaches the user.
Just implement your logic in the interceptor, but only return
from the main view, if needed.
def is_send_permitted(request):
# Check user has required credits in account to these batches.
balance = Account.objects.get(user=request.user).get_balance()
cost_of_sending = Batch.objects.batches_cost_pending(user=request.user)
if balance < cost_of_sending:
return False
else:
return True
@login_required
def process_all(request):
#If we had a POST then get the request post values.
if request.method == 'POST':
batches = Batch.objects.for_user_pending(request)
# Will redirect/cancel request if user does not meet requirements, funds, permissions etc
if not is_send_permitted_interceptor(request):
return HttpResponseForbidden()
# stuff here if everything is ok
You could also raise an Exception here:
from django.core.exceptions import PermissionDenied
raise PermissionDenied()
But it's bad practice to raise exceptions when there is nothing truly exceptional going on.
回答2:
You need to add return
in the caller, because your check function is going to return to the caller, and its value is what you want to return to the browser.
A better approach would be the following:
def is_send_permitted_interceptor(user):
# Check user has required credits in account to these batches.
balance = Account.objects.get(user=user).get_balance()
cost_of_sending = Batch.objects.batches_cost_pending(user=user)
return balance < cost_of_sending
Then in your caller:
if request.method == 'POST':
batches = Batch.objects.for_user_pending(request.user)
if is_send_permitted_interceptor(request.user):
return HttpResponseForbidden()
This way its the view method is where all the redirects happen; and you avoid having to pass around request
.
来源:https://stackoverflow.com/questions/18574151/django-httpresponseforbidden-not-working