Search code examples
djangohttp-redirect

Django redirect not working if called inside a function


I would like to put a redirect command inside of a function and then call this function in a Django view. Can anyone give me a hint why my code below does not redirect?

This redirection works:

views.py

from django.shortcuts import redirect
from django.http import HttpResponse

def my_view(request):
    return redirect("https://stackoverflow.com")
    return HttpResponse("<p>redirection did not work</p>")

This redirection does not work:

views.py

from django.shortcuts import redirect
from django.http import HttpResponse

# define subfunction
def test():
    return redirect("https://stackoverflow.com")

def my_view(request):
    test()
    return HttpResponse("<p>redirection did not work</p>")

Solution

  • In the second example, you're calling the test() function, which performs a redirection, but you're not doing anything with the result of that function call. To ensure the redirection works, you need the result of test() and then return that result from my_view(). As shown below:

    def my_view(request):
        # Call the subfunction and return its result
        return test()