0
0
Djangoframework~5 mins

Redirects with redirect function in Django

Choose your learning style9 modes available
Introduction

Redirects help send users from one page to another automatically. The redirect function makes this easy in Django.

After a user submits a form, send them to a confirmation page.
When a page has moved, send users to the new page.
To protect pages by redirecting users who are not logged in.
After processing data, redirect to avoid resubmitting on refresh.
Syntax
Django
from django.shortcuts import redirect

return redirect(to, *args, permanent=False, **kwargs)

to can be a URL path, a view name, or a model instance.

permanent=True sends a permanent redirect (HTTP 301), otherwise temporary (HTTP 302).

Examples
Redirects to the URL path /home/.
Django
return redirect('/home/')
Redirects to the URL mapped to the view named home in URL configuration.
Django
return redirect('home')
Redirects to the profile view with argument user_id=5.
Django
return redirect('profile', user_id=5)
Redirects to the URL of a model instance if it has a get_absolute_url() method.
Django
return redirect(some_model_instance)
Sample Program

This view checks if the request is a POST (form submitted). If yes, it redirects the user to /thank-you/. Otherwise, it shows a simple message.

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

def my_view(request):
    # Imagine some condition after form submission
    if request.method == 'POST':
        # Redirect to thank you page
        return redirect('/thank-you/')
    return HttpResponse('Please submit the form.')
OutputSuccess
Important Notes

Use redirect to avoid repeating code for sending users to other pages.

Redirects help improve user experience by guiding users smoothly.

Remember to import redirect from django.shortcuts.

Summary

Redirects send users from one page to another automatically.

The redirect function is simple and flexible for this in Django.

You can redirect using URL paths, view names, or model instances.