访问django中Redirect中的变量

时间:2017-05-09 11:34:33

标签: python django django-views django-urls django-login

模板在登录时基于groups呈现。如何在模板中访问这些变量。例如,如何在重定向中访问这些变量,如渲染中的上下文?这是我的代码。 错误是:

  

名称'用户名'未定义

Views.py

def login_user(request):
if request.method == "POST":
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    all_requests= Retest.objects.all() 
    projector_requests = Eventprojector.objects.all()
    classroom_requests = Eventclassroom.objects.all()
    lab_requests = Eventlab.objects.all()
    mikesystem_requests = Eventmikesystem.objects.all()
    extensioncable_requests = Eventextensioncable.objects.all()
    auditorium_requests = Eventauditorium.objects.all()
    graphicshall_requests = Eventgraphicshall.objects.all()
    u = User.objects.get(username=username)




    if user is not None:
        if user.is_active:
            login(request, user)
            if user.groups.filter(name='Rep').exists():
                return redirect('/rep')
            elif
                #..........(other groups)

            else:       
                return render(request, 'retest/login.html', {'error_message': 'Invalid login'})

        else:
            return render(request, 'retest/login.html', {'error_message': 'Your account has been disabled'})
    else:
        return render(request, 'retest/login.html', {'error_message': 'Invalid login'})
  return render(request, 'retest/login.html')
@login_required
def rep(request):

    u=User.objects.get(username=username)
    return render(request, 'retest/home.html', {'u':u})

urls.py

url(r'^$', views.login_user, name='login_user'),
url(r'^rep$', views.rep, name='rep'),

1 个答案:

答案 0 :(得分:1)

当您返回重定向响应时,您告诉浏览器加载新的URL。当浏览器请求新URL时,您将无法再访问新视图中的旧上下文。

如果您需要将信息传递到新网址,可以将其包含在您重定向到的网址中,例如List<Book> books = new ArrayList<>(); CharSequence[] names = books.stream() .map(b -> (CharSequence)b.title) .toArray(CharSequence[]::new); /rep/22/,或在会话中保存数据。

但是,在这种情况下,您不需要这样做,因为您只需使用/rep/?id=22访问登录的用户。

request.user

您甚至不需要在上下文中包含@login_required def rep(request): u = request.user return render(request, 'retest/home.html', {'u':u}) 。由于您使用的是u快捷方式,因此只要启用了身份验证模板上下文处理器,您就应该能够访问模板中的render

{{ user }}