Sobes.tech
Junior — Middle

Explain the concept of redirect in Django and how it is used in web development.

sobes.tech AI

Answer from AI

In Django, a redirect is a mechanism that allows you to send a user from one URL to another. It is typically used after processing a form or changing data to prevent resubmission of the form upon page refresh.

To create a redirect in Django, you use the redirect function from the django.shortcuts module:

from django.shortcuts import redirect

def my_view(request):
    # process data
    return redirect('home')  # redirect to the URL named 'home'

The redirect sends an HTTP response with status code 302 (or another redirect code), and the browser automatically navigates to the new address. This improves UX and helps control the navigation flow within the application.