Django重定向函数为何返回原页面?组详情页跳转异常排查
问题分析与解决
问题描述
网站点击组按钮后,通过POST请求将组名发送至服务器并存入session,预期重定向至/datasheet/intents/详情页,但实际始终停留在原datasheet页面。日志显示详情页已加载,随即又跳转回原页面。
相关代码
URL配置
urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='home'), path('send', send, name='send'), path('datasheet/', datasheet, name='datasheet'), path('datasheet/intents/', intents, name='intents'), ]
视图代码
def datasheet(request): # error handling if 'error' not in request.session: error = "no_error" else: error = request.session['error'] del request.session['error'] # post methods if request.method == 'POST': # show group intents if request.POST['post-function'] == 'details-group': group_name = request.POST['showIntents'] request.session['group'] = group_name print(request.session['group']) return redirect('/intents/') return render(request, './views/datasheet.html', {"error": error}) def intents(request): print("testing, if site opens") return render(request, './views/intents.html')
日志输出
[05/Oct/2022 12:26:48] "POST /datasheet/ HTTP/1.1" 302 0 [05/Oct/2022 12:26:48] "GET /datasheet/intents/ HTTP/1.1" 200 4832 [05/Oct/2022 12:26:48] "GET /datasheet/ HTTP/1.1" 200 3393
前端代码
let group_button = document.getElementsByClassName("groups-details"); // for every Group there is a button to click --> show details for(let i = 0; i<group_button.length; i++){ group_button[i].onclick = function(){ if(group_button[i].type == "button"){ show_intents = group_button[i].value let formData = new FormData(); formData.append('post-function', "details-group"); formData.append('showIntents', show_intents); formData.append('csrfmiddlewaretoken', token); fetch('/datasheet/', { method: 'POST', body: formData, }).then( () => { window.location.reload(); }); } } }
解决步骤
1. 修复后端重定向路径错误
后端当前的重定向路径/intents/是根路径下的,实际目标路径是/datasheet/intents/。建议用Django的reverse方法根据URL name跳转,避免硬编码路径出错:
from django.shortcuts import redirect, reverse # 替换原return语句 return redirect(reverse('intents'))
或者直接使用完整路径:
return redirect('/datasheet/intents/')
2. 修改前端逻辑,移除reload并手动跳转
fetch是异步请求,后端返回的302重定向不会自动触发浏览器跳转,原代码的window.location.reload()会强制刷新原页面,导致跳转后又回到datasheet。修改前端回调,直接跳转到目标页面:
fetch('/datasheet/', { method: 'POST', body: formData, }).then( () => { // 替换reload,直接跳转到详情页 window.location.href = '/datasheet/intents/'; });
3. 问题根源解释
原流程中,浏览器先接收后端的302重定向并加载了/datasheet/intents/,但随后执行window.location.reload(),又重新请求了原/datasheet/页面,因此出现日志中三次请求的现象,最终停留在原页面。
内容的提问来源于stack exchange,提问作者Erbas
相关产品推荐
相关产品推荐

