我在 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/