下面给您详细讲解Django的redirect()函数的作用与使用方法的完整攻略。
redirect()函数属于Django的快捷函数之一,主要作用是重定向到指定的视图函数或URL。其函数定义如下:
def redirect(to, permanent=False, *args, **kwargs):
"""
Return a redirect response to the given URL.
The URL may be a URL name, URL pattern, or the absolute or relative URL of a
view. The scheme of the target URL determines whether to use a temporary or
permanent redirect:
- All HTTP 1.1/1.0 clients understand temporary redirect status codes and
automatically redirect. Redirects are expected to be followed by GET
requests. This makes temporary redirects useful when the URL is
temporarily unavailable (maintenance, etc.).
- Browsers may not recognize all status codes and can only redirect in a
handful of ways. For this reason, permanent redirects are useful to
specify that the resource has moved to a new URL and that all future
requests should be directed there.
:param to: A URL name, URL pattern, or the actual URL to redirect to. If the
URL doesn't contain a scheme (e.g. "example.com"), a server-side
redirect to the same URL is performed.
:type to: str
:param permanent: If ``True``, returns a permanent redirect (HTTP status
code 301) instead of a temporary one (HTTP status code 302).
Defaults to ``False``.
:type permanent: bool
:param args: Any extra arguments to pass to the target view function.
:type args: tuple
:param kwargs: Any extra keyword arguments to pass to the target view
function.
:type kwargs: dict
"""
在项目中,我们可以使用redirect()
函数来跳转到指定的视图函数或URL。下面给出两个实例。
我们为指定的URL设置一个别名,然后使用redirect()
函数将请求重定向到该URL。
1)首先在项目的urls.py
文件中添加一个URL别名:
from django.urls import path
from . import views
urlpatterns = [
path('old_url/', views.old_view, name='old_view'),
]
2)然后在视图函数中使用redirect()
函数将请求重定向到新的URL上。
from django.shortcuts import redirect
def new_view(request):
return redirect('old_view', permanent=True)
我们使用redirect()
函数将请求重定向到一个URL模式,让Django自动匹配并执行对应的视图函数。
1)在项目的urls.py
文件中定义URL模式:
from django.urls import path
from . import views
urlpatterns = [
path('articles/', views.ArticleListView.as_view(), name='article_list'),
path('articles/<int:pk>/', views.ArticleDetailView.as_view(), name='article_detail'),
]
2)在视图函数中使用redirect()
函数将请求重定向到新的URL模式上。
from django.shortcuts import redirect
def index_view(request):
return redirect('article_list')
redirect()
函数是Django的一个快捷函数,主要用于将请求重定向到指定的视图函数或URL。具体来说,我们可以使用该函数跳转到URL别名、URL模式或URL地址等。
本文链接:http://task.lmcjl.com/news/16251.html