i'm trying to create a simple API on Django, and this is my first. The class User get the AbstractUser, like this:
from django.db import models
from django.contrib.auth.models import AbstractUser
class Usuario(AbstractUser):
nome = models.CharField(max_length = 255)
username = models.CharField(max_length=150, unique=True, blank=False, null=False, default="")
nascimento = models.DateField()
password = models.CharField(max_length=128, blank=False, null=False, default="")
But when I try to authenticate, the method allways returns None. Why? I checked, on DataBase, and the Users are already there.
from django.shortcuts import render, redirect
from conta.models import Usuario
import secrets
from django.contrib.auth import authenticate, login
def login_view(request):
if request.method == "POST":
user = request.POST.get("user")
senha = request.POST.get("password")
autenticador = authenticate(request, username=user, password=senha)
if autenticador is None:
context = {"error" : "Invalid username or password"}
return render(request, "conta/tela_de_login.html", context)
login(request, autenticador)
redirect('/admin')
return render(request, "conta/tela_de_login.html", {})
CodePudding user response:
You are likely comparing user object with username, which is string. Try this:
autenticador = authenticate(request, username=user.username, password=senha)
CodePudding user response:
Chack this is :-
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username = username, password = password)
if user is not None:
login(request, user)
messages.success(request, f' wellcome {username} !!')
return redirect('admin')
else:
messages.warning(request, f'Invalid username or password')
return render(request, "conta/tela_de_login.html", {})
But i don't understand why you redirect "admin page after login.