返回将您带到 Django 的页面

Dom*_*nic 2 python django formview

在 Python/Django 中,我有一个 FormView,它允许您临时添加某些字段选择。

(示例:从苏打水下拉列表中选择苏打水)

选择最喜欢的苏打水:[_Soda_Choices_Dropdown_] +添加苏打水

我希望能够即时添加苏打水,当我保存苏打水时,我希望成功 URL 是将您带到那里的页面。

【第1页】-->【新建汽水FormView】--成功->【第1页】

实现这一目标的最佳方法是什么?

谢谢!

Rah*_*pta 7

编辑:

最好在请求中使用next参数重定向到购买我们表单页面的页面,而不是使用HTTP_REFERER.

假设您在页面some_page.html上有指向该MySodaFormView页面的链接。在这里,request.path作为next参数传递。这将在重定向时使用。

<a href='/my/soda/form/page/?next={{request.path}}'>Create new soda</a> 
Run Code Online (Sandbox Code Playgroud)

然后在MySodaFormView渲染页面时,next在上下文中传递参数。此参数将在form操作中传递并在重定向时使用。

在您的 soda 表单视图模板中,next在表单中指定参数action

<form method="POST" action="/my/soda/form/page/?next={{next_url}}">
Run Code Online (Sandbox Code Playgroud)

您的视图将类似于:

class MySodaFormView(FormView):

    def get_context_data(self, **kwargs):
        context = super(MySodaFormView, self).get_context_data(**kwargs)
        context['next_url'] = self.request.GET.get('next') # pass `next` parameter received from previous page to the context 
        return context

    def get_success_url(self):
        next_url = self.request.GET.get('next')
        if next_url:
            return next_url # return next url for redirection
        return other_url # return some other url if next parameter not present
Run Code Online (Sandbox Code Playgroud)

编辑:下面使用的方法HTTP_REFERER有时可能不起作用,因为某些浏览器关闭了传递引用功能或为用户提供禁用该功能的选项。

要返回在那里为您购买的页面,您可以使用字典中的HTTP_REFERER标题HttpRequest.META

HttpRequest.META是一个标准的 Python 字典,包含所有可用的 HTTP 标头。其中的标题之一是HTTP_REFERER包含引用页面(如果有)。

由于您正在使用FormView,您可以覆盖该get_success_url()功能以成功重定向到将用户购买到的页面MySodaFormView。我们将使用的价值得到这个页面HTTP_REFERERrequest.META字典。

from django.views.generic.edit import FormView

class MySodaFormView(FormView):

    def get_success_url(self):
        referer_url = self.request.META.get('HTTP_REFERER') # get the referer url from request's 'META' dictionary
        if referer_url:
            return referer_url # return referer url for redirection
        return other_url # return some other url if referer url not present
Run Code Online (Sandbox Code Playgroud)

注意:使用HTTP_REFERERfrom request.METAdictionary 可能不是“最佳实践”,因为某些浏览器已关闭传递引用功能或为用户提供禁用该功能的选项。在这种情况下,您的重定向将无法正常工作。您可以改为?next=在 url 和get_success_url()函数中传递一个参数,使用 的值next来获取要重定向到的 url。