Home > Software design >  The login function in Django not working properly
The login function in Django not working properly

Time:02-20

views.py

def login_view(request):
    form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username,
                                password=password)
            if user is not None:
                login(request,user)
                messages.info(request,'登入成功!')
                return redirect('index')
            else:
                messages.error(request,'帳戶無效或密碼錯誤! 請重試!')
        else:
            messages.error(request,'帳戶無效或密碼錯誤! 請重試!')
    context = {'form':form}
    return render(request,'customer/login.html',context)

login.html

<form method="POST" action="" style="position:absolute;top:300px;left:125px;">
        {% csrf_token %} 
        {{ form.username|as_crispy_field }}<br>
        {{ form.password|as_crispy_field }}<br>
        <button  type="submit">登入</button>
</form>

For the login function in Django, I am trying to use the username and password based on the User model in django.contrib.auth.models to login into the account. However, even though I am using my superuser status to login and the error message appears showing that invalid username or password. May I ask is AuthenticationForm following the User model information to authenticate the user or anything I am missing?

CodePudding user response:

You need to provide the 'data' attribute to the AuthenticationForm. Try this:

def login_view(request):
    form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            login(request, form.get_user())
            messages.info(request,'登入成功!')
            return redirect('index')
        else:
            messages.error(request,'帳戶無效或密碼錯誤! 請重試!')
    context = {'form':form}
    return render(request,'customer/login.html',context)

The AuthenticationForm already does the authentication for you, so there is no need to run the authenticate function in your code again. You can get the user object for logging in using form.get_user() if the form is valid.

  • Related