2016-06-10 77 views
2

我有下面的代碼,我得到一個錯誤說:「用戶對象有沒有屬性POST」如何使用Django登錄

def login (request): 
    username = request.POST['username'] 
    password = request.POST['password'] 
    user = authenticate(username=username, password=password) 
    if user is not None: 
     if user.is_active: 
      login(user) 
      return render(request, 'base_in/base_in.html', {}) 
     else: 
      return render(request, 'signupapp/error.html', {'message':'the acount is not active'}) 
    else: 
     return render(request, 'signupapp/error.html', {'message':'username and password is incorrect'}) 

我也試過這個代碼,並得到了另一個錯誤:「登錄()需要1個位置參數,但2個被給出「

def login (request): 
    username = request.POST['username'] 
    password = request.POST['password'] 
    user = authenticate(username=username, password=password) 
    if user is not None: 
     if user.is_active: 
      login(user) 
      return render(request, 'base_in/base_in.html', {}) 
     else: 
      return render(request, 'signupapp/error.html', {'message':'the acount is not active'}) 
    else: 
     return render(request, 'signupapp/error.html', {'message':'username and password is incorrect'}) 

我在做什麼錯?基於Django的教程,它應該正常工作:

https://docs.djangoproject.com/en/1.9/topics/auth/default/#how-to-log-a-user-in

回答

3

發生了什麼事是你試圖調用from django.contrib.authlogin,但你也定義自己的函數調用login(),你有一種名稱衝突的位置。

您應該將其重命名爲其他內容,例如login_view()

from django.contrib.auth import authenticate, login 

def login_view(request): # If you call it login, 
         # you get conflict with login imported aove 
    # The rest of your code here 
    # now if you call login(user), it will use the correct one, 
    # i.e. the one imported from django.contrib.auth 

如果你不喜歡重命名,你可以導入Django的login下一個不同的名稱,如

from django.contrib.auth import login as auth_login 

# Then use auth_login(user) in your code 
0

我會建議增加一個登錄表單第一

class LoginForm(forms.Form): 
    username = forms.CharField() 
    password = forms.CharField(widget=forms.PasswordInput)#hides password on input 

然後

from django.http import HttpResponseRedirect,HttpResponse 
from django.contrib.auth import authenticate, login 
. 
. 


def user_log(request): 
    #if you add request.method=='POST' is it a bug i dont know y 
    if request.method: 
    form = LoginForm(request.POST) 
    if form.is_valid(): 
     cleandata=form.cleaned_data 
     #authenticate checks if credentials exists in db 
     user=authenticate(username=cleandata['username'], 
          password=cleandata['password']) 
     if user is not None: 
      if user.is_active: 
       login(request, user) 
       return HttpResponseRedirect("your template") 
      else: 
       return HttpResponseRedirect("your templlate") 
     else: 
      return HttpResponse("Invalid login") 
    else: 
     form=LoginForm() 
    return render(request, 'registration/login.html',{'form':form}) 
+0

你能解釋爲什麼它更好地在表單中添加相應的日誌,而我可以用django.contrib中。 auth.models.User並有一個登錄模板? –

+0

@bakkal答案是最好的。但與你類似,我遇到了同樣的問題,即我如何解決它。 –