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.
Aucun commentaire:
Enregistrer un commentaire