Django中重定向时如何传递数据?
问题:重定向时传递链接信息到clientPage页面
我通过链接实现客户端授权,认证逻辑如下:
def ClientAuth(request, link_code): try: code = Links.objects.filter(code=link_code).values('code', 'status') if code[0]['status']: username, password = 'Client', '**************' client = authenticate(request, username=username, password=password) if client is not None: login(request, client) return redirect('clientPage') return HttpResponse("Hello its work") else: return render(request, 'client/404.html') except: return render(request,'client/404.html')
URL配置:
urlpatterns = [ path('clientPage/',views.clientPage, name = 'clientPage'), path('<link_code>/', views.ClientAuth, name='ClienAuth') ]
客户端通过不同链接登录后,需要在clientPage页面获取对应链接的信息(比如链接ID),当前clientPage代码:
def clientPage(request): print(request) return HttpResponse("Hello")
请问如何在ClientAuth重定向时传递该数据?
解决方案
方法1:通过Session存储链接信息(推荐,不暴露URL参数)
利用Django的Session机制,在认证通过后将链接相关数据存入Session,后续在clientPage中读取。
修改ClientAuth视图:
def ClientAuth(request, link_code): try: # 查询包含所需字段的链接对象 link_query = Links.objects.filter(code=link_code).first() if link_query and link_query.status: username, password = 'Client', '**************' client = authenticate(request, username=username, password=password) if client is not None: login(request, client) # 将链接ID和code存入session request.session['link_id'] = link_query.id request.session['link_code'] = link_query.code return redirect('clientPage') return HttpResponse("Hello its work") else: return render(request, 'client/404.html') except: return render(request,'client/404.html')
修改clientPage视图读取Session:
def clientPage(request): # 从session中获取链接信息 link_id = request.session.get('link_id') link_code = request.session.get('link_code') # 根据link_id查询数据库获取完整信息 if link_id: link = Links.objects.get(id=link_id) return HttpResponse(f"Hello, 当前链接ID: {link_id}, 链接码: {link.code}") return HttpResponse("未获取到链接信息")
方法2:通过URL参数传递链接信息(URL会暴露参数)
修改URL配置,给clientPage添加参数路径:
urlpatterns = [ path('clientPage/<int:link_id>/', views.clientPage, name='clientPage'), path('<link_code>/', views.ClientAuth, name='ClienAuth') ]
修改ClientAuth重定向时传递参数:
def ClientAuth(request, link_code): try: link_query = Links.objects.filter(code=link_code).first() if link_query and link_query.status: username, password = 'Client', '**************' client = authenticate(request, username=username, password=password) if client is not None: login(request, client) # 重定向时传递link_id参数 return redirect('clientPage', link_id=link_query.id) return HttpResponse("Hello its work") else: return render(request, 'client/404.html') except: return render(request,'client/404.html')
修改clientPage视图接收参数:
def clientPage(request, link_id): # 根据link_id查询链接信息 link = Links.objects.get(id=link_id) return HttpResponse(f"Hello, 当前链接ID: {link_id}, 链接码: {link.code}")
补充:修复原代码潜在问题
原代码中使用code[0]['status'],如果filter返回空QuerySet会触发索引错误,建议改为先判断查询结果是否存在,如上述方案中使用first()和if link_query的写法。
内容的提问来源于stack exchange,提问作者juniorDev
相关产品推荐
相关产品推荐

