Sebastian Nin
Sebastian Nin

Reputation: 302

Why does it shows error in the log in form in Django?

I'm trying to create a website with a log in and registration form in django, the registration works well, it saves the accounts in the database, but when I try to log in, it doesn't work at all, here's the code:

views.py

from django.shortcuts import render
from .forms import UserForm
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse


# Create your views here.
def index(request):
    return render(request, 'app1/index.html')

@login_required
def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('index'))

def register(request):

    registered = False

    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            registered = True
        else:
            print(user_form.errors)
    else:
        user_form = UserForm()

    return render(request, 'app1/register.html',{'user_form':user_form, 'registered':registered})

def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password = password)

        if user:
            if user.is_active:
                login(request, username)
                return HttpResponseRedirect(reverse('index'))
            else:
                return HttpResponse("Account Not Active")
        else:
            print("Someone tried to login and failed")
            print(f"Username: {username} and password {password}")
            return HttpResponse ("Invalid Login details supplied")
    else:
        return render(request, 'app1/login.html')

models.py

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class UserProfileInfo(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class UserForm(UserCreationForm):
    email = forms.EmailField(max_length=40, help_text='Required')
    

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

I hope that someone could help me because I believe that the error is in the views.py, but I'm not sure where.

Upvotes: 2

Views: 303

Answers (2)

Pruthvi Barot
Pruthvi Barot

Reputation: 2018

in login function we have to pass user not username so in user_login function

if user:
    if user.is_active:
        login(request, user)
        return HttpResponseRedirect(reverse('index'))
    else:
        return HttpResponse("Account Not Active")

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477437

A UserCreationForm already hashes the password by calling set_password, hence calling it a second time, will double hash it. You thus should remove the user.set_password(user.password) line:

def register(request):
    registered = False
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            # do not hash a second time
            #  user.set_password(user.password)
            user = user_form.save()
            
            registered = True
        else:
            print(user_form.errors)
    else:
        user_form = UserForm()

    return render(request, 'app1/register.html',{'user_form':user_form, 'registered':registered})

Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.

Upvotes: 2

Related Questions