Returning multiple times in Django views and proceed code execution

Viewed 700

How can I return something and still proceed? In this case, Hello World should be printed in the console. I want to keep the return because i need to execute a function that returns either None or an Httpresponse

def filter_pending_documents(request):
    return pass #code should not stop here
    print('Hello World')
    return HttpResponse('')
3 Answers

Whenever your function reaches a return statement, it will exit out of the function.

So, in your case, you want to remove that line from your code for it to work, as

def filter_pending_documents(request):
    print('Hello World')
    return HttpResponse('')

if you need your function to return either None or the HttpResponse, you need to provide a condition for each case (an if statement). Remember, if the function reaches any return statement, it will exit out. One example to achieve what you want is as follows

def filter_pending_documents(request):
    print("Hello World!")
    if 2 > 1: # replace with your own condition
        return None
    else:
        return HttpResponse('')

Just remove the return pass from there and it will work fine

When a function reaches a return statement it will break even if there is code after

remove the pass statement because it used on an empty class, function, if and for block for different purposes and make sure you iport the HttpResponse like from django.http import HttpResponse

def filter_pending_documents(request):
    string = 'Hello World'
    return HttpResponse(string)

or you can not the returning object in the variable like

def filter_pending_documents(request):          
    return HttpResponse('Hello World')

or create the markup page in the template and render it like this

def filter_pending_documents(request):
    return render(request, 'hello world.html')
Related