python - 获取下一个 View 中如何使用 HttpRedirect 调用 View

标签 python django redirect

我在 django 中有两个 View :一个加载页面,一个保存表单。我已将两者分开,这样我就可以保留在同一页面上,而不会因页面刷新而导致重新提交。

保存表单的创建 View 重定向回使用HttpResponseRedirect加载页面的 View 。

是否可以在加载页面 View 中获取该 View 是否是由带有重定向的创建 View 调用的?

所以:

def holiday(request, value=None, year=None, month=None):
    if request.method == "GET":
        # set some variables for the view
        year = something
        month = something_else
    else:
        # get if the view was executed from a redirect
        # set year and month to be something2 and something_else2

    # calendar

    holidayform = HolidayForm(request.POST or None, request.FILES or None)
    context = {
        "holidayform": holidayform,
        "calendar": mark_safe(cal),
        "year": year,
        "month": month,
    }
    return render(request, "tande/calendar.html", context)

然后是保存表单的 View :

def create_holiday(request):
    overlapping_dates = False
    if request.method == "POST":

        #save the form... or don't

        return HttpResponseRedirect(reverse("tande:holiday"))

最佳答案

HttpResponseRedirect 将按字面意思重定向用户。基本上,就好像用户在浏览器中输入 URL 并按 Enter 键一样。这意味着过去请求中的某些信息将不可用。

https://docs.djangoproject.com/en/1.10/ref/request-response/#httpresponse-subclasses

您可以通过 GET 参数传递标志。它会成功:

HttpResponseRedirect(reverse("tande:holiday") + '?redirect=True')

然后在您的 form_view 中读取 GET 参数:

if request.GET.get('redirect', None):
    do_something()

您只需考虑如果用户故意将 GET 参数添加到 URL 中会发生什么。他可以伪造结果。如果您的意图是显示一条消息,那么这不会有问题。

关于python - 获取下一个 View 中如何使用 HttpRedirect 调用 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42411488/

相关文章:

python - 无法从给定的 python 代码生成 S=>Ba

python 导入站点失败

Python win32com - 自动化 Word - 如何替换文本框中的文本?

php - 如何使用 .htaccess 从非安全版本的站点重定向到安全版本的站点

python - 自定义 linux 守护进程不会停止使用 "service stop"

python - 如何在 jinja 标签内使用 jinja 标签

django - "The connection was reset"在本地主机 :8000 using django and docker

php - 执行代码后重定向

python - 如何将 Python 控制台输出重定向到 QTextBox

sql - 将 get_absolute_url 组合成 django 中的原始 SQL 语句