gpt4 book ai didi

python - 如何结合 HttpResponseRedirect 和 render_to_response?

转载 作者:行者123 更新时间:2023-11-28 21:52:48 26 4
gpt4 key购买 nike

当用户登录时,他被 HttpResponseRedirect 重定向到“/welcome/”url。但我也想返回下面注释掉的语句,因为我也想将字典传递给模板。帮我想出一种方法来组合这两个语句或任何其他解决方案。

View .py

   def home(request):
templatename="login.html"
if request.method=="POST":
u=request.POST.get("username")
p=request.POST.get("password")
user=authenticate(username=u, password=p)
if user is not None:
if user.is_active:
print "This User is valid, active and authenticated"
login(request,user)
state = "You're successfully logged in!"
return HttpResponseRedirect("/welcome/")
#return render_to_response(templatename,{'state':state, 'user':user}, context_instance=RequestContext(request))


else:
print "This User is valid but the account has been disabled"
state="This User is valid but the account has been disabled"

else:
print "The Username and Password entered were incorrect"
state = "Your username and/or password were incorrect."
#return render_to_response(templatename,{'state':state, 'user':user}, context_instance=RequestContext(request))

else:
user=None
state=None

return render_to_response(templatename, {'state':state, 'user':user}, context_instance=RequestContext(request))

最佳答案

您可以为此使用消息框架 .. from django.contrib import messages

views.py

messages.success(request, "You're successfully logged in!")
return HttpResponseRedirect("/welcome/")

另一种选择就是为此使用 session 。!但在 session 中你会找到显示后隐藏消息的方法......

#views.py
request.session['state'] = "You're successfully logged in!"
HttpResponseRedirect("/welcome/")
#html
{{ request.session.state }}

关于python - 如何结合 HttpResponseRedirect 和 render_to_response?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27740350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com