gpt4 book ai didi

python - 返回到将您带到那里的页面 Django

转载 作者:行者123 更新时间:2023-12-02 15:24:08 25 4
gpt4 key购买 nike

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

(Example: Selecting a soda from the soda dropdown)

Select Favorite soda: [_Soda_Choices_Dropdown_] +Add soda

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

[第1页] --> [新建soda FormView] --成功-> [第1页]

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

谢谢!

最佳答案

编辑:

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

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

<a href='/my/soda/form/page/?next={{request.path}}'>Create new soda</a> 

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

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

<form method="POST" action="/my/soda/form/page/?next={{next_url}}">

你的 View 看起来像这样:

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

编辑:以下使用 HTTP_REFERER 的方法有时可能无法正常工作,因为某些浏览器已关闭传递引荐来源网址功能或为用户提供禁用该功能的选项。

要返回到那里的页面,您可以使用 HttpRequest.META 中的 HTTP_REFERER header 词典。

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

由于您使用的是 FormView,您可以覆盖 get_success_url() 函数以在成功时重定向到将用户购买到 MySodaFormView。我们将使用 request.META 字典中 HTTP_REFERER 的值获取此页面。

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

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

关于python - 返回到将您带到那里的页面 Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31766235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com