django重定向_Django重定向最终指南

django重定向

When you build a Python web application with the Django framework, you’ll at some point have to redirect the user from one URL to another.

当使用Django框架构建Python Web应用程序时,您将不得不将用户从一个URL重定向到另一个URL。

In this guide, you’ll learn everything you need to know about HTTP redirects and how to deal with them in Django. At the end of this tutorial, you’ll:

在本指南中,您将学习有关HTTP重定向以及如何在Django中进行处理所需的所有知识。 在本教程的最后,您将:

  • Be able to redirect a user from one URL to another URL
  • Know the difference between temporary and permanent redirects
  • Avoid common pitfalls when working with redirects
  • 能够将用户从一个URL重定向到另一个URL
  • 了解临时重定向和永久重定向之间的区别
  • 使用重定向时避免常见的陷阱

This tutorial assumes that you’re familiar with the basic building blocks of a Django application, like views and URL patterns.

本教程假定您熟悉Django应用程序的基本构建块,例如viewURL pattern

Django重定向:一个超级简单的示例 (Django Redirects: A Super Simple Example)

In Django, you redirect the user to another URL by returning an instance of HttpResponseRedirect or HttpResponsePermanentRedirect from your view. The simplest way to do this is to use the function redirect() from the module django.shortcuts. Here’s an example:

在Django中,您可以通过从视图返回HttpResponseRedirectHttpResponsePermanentRedirect实例来将用户重定向到另一个URL。 最简单的方法是使用django.shortcuts模块中的redirect()函数。 这是一个例子:

 # views.py
# views.py
from from django.shortcuts django.shortcuts import import redirect

redirect

def def redirect_viewredirect_view (( requestrequest ):
    ):
    response response = = redirectredirect (( '/redirect-success/''/redirect-success/' )
    )
    return return response
response

Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view.

只需在视图中调用带有URL的redirect() 。 它将返回HttpResponseRedirect类,然后从视图中返回该类。

A view returning a redirect has to be added to your urls.py, like any other view:

与其他视图一样,必须将返回重定向的视图添加到urls.py

Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/.

假设这是Django项目的主要urls.py ,URL /redirect/现在重定向到/redirect-success/

To avoid hard-coding the URL, you can call redirect() with the name of a view or URL pattern or a model to avoid hard-coding the redirect URL. You can also create a permanent redirect by passing the keyword argument permanent=True.

为避免对URL进行硬编码,可以使用视图或URL模式或模型的名称调用redirect()来避免对重定向URL进行硬编码。 您还可以通过传递关键字参数permanent=True来创建永久重定向。

This article could end here, but then it could hardly be called “The Ultimate Guide to Django Redirects.” We will take a closer look at the redirect() function in a minute and also get into the nitty-gritty details of HTTP status codes and different HttpRedirectResponse classes, but let’s take a step back and start with a fundamental question.

本文可能到此结束,但之后很难称为“ Django重定向的终极指南”。 我们将在一分钟内仔细研究redirect()函数,并深入了解HTTP状态代码和不同的HttpRedirectResponse类的细节,但让我们退后一步,从一个基本问题开始。

为什么要重定向 (Why Redirect)

You might wonder why you’d ever want to redirect a user to a different URL in the first place. To get an idea where redirects make sense, have a look at how Django itself incorporates redirects into features that the framework provides by default:

您可能想知道为什么首先要将用户重定向到其他URL。 要了解重定向在哪里有意义,请查看Django本身如何将重定向合并到框架默认提供的功能中:

  • When you are not logged-in and request a URL that requires authentication, like the Django admin, Django redirects you to the login page.
  • When you log in successfully, Django redirects you to the URL you requested originally.
  • When you change your password using the Django admin, you are redirected to a page that indicates that the change was successful.
  • When you create an object in the Django admin, Django redirects you to the object list.
  • 当您未登录并请求需要身份验证的URL(例如Django admin)时,Django会将您重定向到登录页面。
  • 成功登录后,Django会将您重定向到您最初请求的URL。
  • 使用Django管理员更改密码时,您将被重定向到一个指示更改成功的页面。
  • 在Django管理员中创建对象时,Django会将您重定向到对象列表。

What would an alternative implementation without redirects look like? If a user has to log in to view a page, you could simply display a page that says something like “Click here to log in.” This would work, but it would be inconvenient for the user.

没有重定向的替代实现是什么样的? 如果用户必须登录才能查看页面,则只需显示一个页面,上面写着“单击此处登录”。 这将起作用,但是对于用户而言将是不便的。

URL shorteners like http://bit.ly are another example of where redirects come in handy: you type a short URL into the address bar of your browser and are then redirected to a page with a long, unwieldy URL.

http://bit.ly这样的URL缩短器是重定向很方便的另一个示例:您在浏览器的地址栏中输入一个简短的URL,然后重定向到带有冗长的URL的页面。

In other cases, redirects are not just a matter of convenience. Redirects are an essential instrument to guide the user through a web application. After performing some kind of operation with side effects, like creating or deleting an object, it’s a best practice to redirect to another URL to prevent accidentally performing the operation twice.

在其他情况下,重定向不只是为了方便。 重定向是引导用户浏览Web应用程序的重要工具。 在执行了一些具有副作用的操作(例如创建或删除对象)之后,最佳做法是重定向到另一个URL,以防止两次意外执行该操作。

One example of this use of redirects is form handling, where a user is redirected to another URL after successfully submitting a form. Here’s a code sample that illustrates how you’d typically handle a form:

这种使用重定向的示例是表单处理,其中,用户在成功提交表单后将重定向到另一个URL。 这是一个代码示例,说明您通常如何处理表单:

 from from django django import import forms
forms
from from django.http django.http import import HttpResponseRedirect
HttpResponseRedirect
from from django.shortcuts django.shortcuts import import redirectredirect , , render

render

def def send_messagesend_message (( namename , , messagemessage ):
    ):
    # Code for actually sending the message goes here

# Code for actually sending the message goes here

class class ContactFormContactForm (( formsforms .. FormForm ):
    ):
    name name = = formsforms .. CharFieldCharField ()
    ()
    message message = = formsforms .. CharFieldCharField (( widgetwidget == formsforms .. TextareaTextarea )

)

def def contact_viewcontact_view (( requestrequest ):
    ):
    # The request method 'POST' indicates
    # The request method 'POST' indicates
    # that the form was submitted
    # that the form was submitted
    if if requestrequest .. method method == == 'POST''POST' :  :  # 1
        # 1
        # Create a form instance with the submitted data
        # Create a form instance with the submitted data
        form form = = ContactFormContactForm (( requestrequest .. POSTPOST )  )  # 2
        # 2
        # Validate the form
        # Validate the form
        if if formform .. is_validis_valid (): (): # 3
            # 3
            # If the form is valid, perform some kind of
            # If the form is valid, perform some kind of
            # operation, for example sending a message
            # operation, for example sending a message
            send_messagesend_message (
                (
                formform .. cleaned_datacleaned_data [[ 'name''name' ],
                ],
                formform .. cleaned_datacleaned_data [[ 'message''message' ]
            ]
            )
            )
            # After the operation was successful,
            # After the operation was successful,
            # redirect to some other page
            # redirect to some other page
            return return redirectredirect (( '/success/''/success/' )  )  # 4
    # 4
    elseelse :  :  # 5
        # 5
        # Create an empty form instance
        # Create an empty form instance
        form form = = ContactFormContactForm ()

    ()

    return return renderrender (( requestrequest , , 'contact_form.html''contact_form.html' , , {
     {
      'form''form' : : formform })
})

The purpose of this view is to display and handle a contact form that allows the user to send a message. Let’s follow it step by step:

该视图的目的是显示和处理允许用户发送消息的联系表单。 让我们逐步进行操作:

  1. First the view looks at the request method. When the user visits the URL connected t

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值