как использовать логин django

У меня есть следующий код, и я получаю сообщение об ошибке: «У объекта User нет атрибута POST»

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'})

Я также попробовал этот код и получил еще одну ошибку: «login () принимает 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


person The Monster    schedule 10.06.2016    source источник


Ответы (2)


Произошло следующее: вы пытаетесь вызвать login из from django.contrib.auth, но вы также определяете свою собственную функцию с именем 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

Если вы предпочитаете не переименовывать, вы можете импортировать login Django под другим именем, например

from django.contrib.auth import login as auth_login

# Then use auth_login(user) in your code
person bakkal    schedule 10.06.2016

Я бы посоветовал сначала добавить форму входа

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})
person 0n10n_    schedule 10.06.2016
comment
Можете ли вы объяснить, почему лучше добавить форму входа в систему, в то время как я могу использовать django.contrib.auth.models.User и иметь шаблон входа в систему? - person The Monster; 10.06.2016
comment
Ответ @bakkal - лучший, но, как и вы, я столкнулся с той же проблемой, что и решил. - person 0n10n_; 10.06.2016