当用户登录时,HttpResponseRedirect会将其重定向到“/welcome/”url。但我也希望返回下面注释掉的语句,因为我还希望将字典传递给模板。请帮助我结合这两个语句或任何其他解决方案的方法。
视图.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
视图.py

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

另一个选择就是使用会话。!但是在会话中,你会发现在显示。。。
#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/

10-12 16:47