How to redirect from a view to another view In Django

As already suggested by @mdegis you can use the Django redirect function to redirect to another view or url.

from django.shortcuts import redirect

def view_to_redirect_to(request):
    #This could be the view that handles the display of created objects"
    ....
    perform action here
    return render(request, template, context)

def my_view(request):
    ....
    perform form action here
    return redirect(view_to_redirect_to)

Read more about redirect here and here

You can pass positional or keyword argument(s) to the redirect shortcut using the reverse() method and the named url of the view you’re redirecting to.

In urls.py

from news import views

url(r'^archive/$', views.archive, name="url_to_redirect_to")

In views.py

from django.urls import reverse

def my_view(request):
    ....
    return redirect(reverse('url_to_redirect_to', kwargs={'args_1':value}))

More about reverse Here

Leave a Comment