2016-02-26 84 views
0

所以我在我的base.html註冊,然後表單重定向到註冊頁面。如何通過重定向傳入變量?

def signIn(request): 
    if request.user.is_authenticated(): 
     context = { 
      "extendVar":"baseLoggedIn.html", 
     } 
     return HttpResponseRedirect("out") 
    if request.user.is_authenticated()==False: 
     # form=SignUpForm(request.POST or None) 
     if request.method=="POST": 

      email=request.POST.get('email','') 
      password = request.POST.get('password','') 

      user = auth.authenticate(username=email,password=password) 

      print(email) 
      print(password) 
      print(user) 
      if user is not None: 
       print("notNone") 
       auth.login(request,user) 
       return HttpResponseRedirect("out") 
      else: 
       print("None quàlol") 
       context={ 
        "failure":"Password and e-mail did not match", 
       } 
       return HttpResponseRedirect("out") #redirects to base.html 
     context = { 
      "extendVar":"baseNotLoggedIn.html", 
     } 
    return render(request, "base.html",context) 

唯一的問題是,當我這樣做,它重定向到主頁,但主頁上沒有任何錯誤,我無法想出一個辦法來顯示錯誤的密碼+電子郵件不匹配,因爲我重定向。

回答

0

您需要將您的消息作爲上下文的一部分傳遞,並且您的HttpResponseRedirect不將任何上下文作爲參數,因此您需要return render(request, "base.html", context)而不是HttpResponseRedirect。然後,您可以從context訪問"failure"密鑰。

此外,請保持您的代碼清潔!

def sign_in(request): 
    if request.user.is_authenticated(): 
     context = { 
      "extendVar":"baseLoggedIn.html", 
     } 
     return HttpResponseRedirect("out") 
    else: 
     if request.method == "POST": 
      form = SignUpForm(request.POST) 
      if form.is_valid(): 
       email = form.cleaned_data['email'] 
       password = form.cleaned_data['password'] 

       user = auth.authenticate(username=email, password=password) 

       print(email) 
       print(password) 
       print(user) 
       if user: 
        print("notNone") 
        auth.login(request, user) 
        return HttpResponseRedirect("out") 
       else: 
        print("None quàlol") 
        context={ 
         "failure":"Password and e-mail did not match", 
        } 
        return render(request, "base.html", context) 
      else: # form invalid, pass as variable back to user with form errors 
       return render(request, "base.html", {'form': form} 
     context = { 
      "extendVar":"baseNotLoggedIn.html", 
     } 
    return render(request, "base.html",context) 
+0

確定,唯一的問題是我有我的base.html文件其不被延長,因爲我只是在原來的形式擴展它的形狀......這是一個有點麻煩把它放在2立即放置。有沒有更優雅的方式來做到這一點?此外,我會做你喜歡的形式,但這種形式僅用於登錄,並沒有forms.py或類似的東西。我仍然可以做,如果form.is_valid()等? – swedishfished