📜  django httpresponseredirect - Python (1)

📅  最后修改于: 2023-12-03 14:40:46.252000             🧑  作者: Mango

Django HttpResponseRedirect

When building web applications, it's common to redirect users from one URL to another. In Django, you can use the HttpResponseRedirect class to achieve this.

How to use HttpResponseRedirect

To use HttpResponseRedirect, first import it from the django.http module:

from django.http import HttpResponseRedirect

Next, use it in a view function. Here's an example:

def my_view(request):
    # Do some processing...
    
    return HttpResponseRedirect('/redirect-url/')

In this example, the view function redirects the user to the URL "/redirect-url/". You can also use variable paths with url parameters:

def my_view(request):
    # Do some processing...
    
    return HttpResponseRedirect('/redirect-url/{}/'.format(pk))
Redirecting to named urls

You can also redirect to named urls, which are defined in your urls.py file. To do this, use the reverse() function to get the url by name:

from django.urls import reverse

def my_view(request):
    # Do some processing...
    
    return HttpResponseRedirect(reverse('myapp:myview'))

In this example, myapp:myview is the name of the url that we want to redirect to. reverse() will automatically generate the correct url based on the name.

Redirecting with a status code

You can also specify a status code for the redirect using the HttpResponseRedirect constructor. For example, to perform a permanent redirect (301), do:

return HttpResponseRedirect('/redirect-url/', permanent=True)
Conclusion

HttpResponseRedirect is a useful class in Django for redirecting users from one URL to another. With this class, you can redirect users using either a relative or an absolute URL, and you can even redirect them to named urls.