【发布时间】:2020-04-24 01:16:18
【问题描述】:
我有一个系统,其中大部分功能取决于用户设置的会话 cookie。自然地,我允许轻松更改此会话(属性),以便用户可以在浏览整个应用程序时无缝地查看新信息。
例如,用户正在查看系统中的单位,当他们选择一个新属性时,将显示新选择的属性的单位。很简单。但是,有一种情况是用户正在查看一个单元并且他们更改了一个属性。显然,他们正在查看的单元不再找到,所以页面 404 的。
我想知道重定向将 404,以便我可以将它们重定向到主页。我该怎么做?
我能想到的所有检查方式(即解析或 HttpRespsonse)都不会显示错误。
from urllib.parse import urlparse
import requests
from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import redirect, get_object_or_404
from django.urls import reverse, resolve, Resolver404
from apps.properties.models import Property
def set_property_session(request, property_id):
redirect_url = request.META.get('HTTP_REFERER')
# to check if it resolves, we must gather the path from the url
path_to_check = urlparse(redirect_url).path
try:
# check to ensure the path resolves
resolve(path_to_check)
response = HttpResponse(path_to_check)
# 200, not 404, when it should be while I am testing
print(response.status_code)
print(f'{path_to_check} is a valid path for redirection, we are going to go there in a sec...')
except Resolver404:
# error so go back home
redirect_url = reverse('home', args=[client_url])
print(f'{path_to_check} is not a valid path')
return redirect(redirect_url)
# 0 means the user wants to clear their session
if property_id == 0:
request.session['property'] = None
Logger.info('property session set to none')
else:
# set the session to whichever property the user wants
request.session['property'] = get_object_or_404(Property, pk=property_id)
return redirect(redirect_url)
【问题讨论】:
标签: python django python-3.x django-views http-status-code-404