Django authenticate() always returns None

I am building a web project with Django to facilitate distribution in case of an earthquake. The user needs to be a member as a Mukhtar or a Helper. The registration system works successfully. But the login part is constantly returning None value even though my login information is absolutely correct.

models.py:

from django.db import models
from django.contrib.auth.models import AbstractUser
from base64 import b32encode
from hashlib import sha1
from random import random

# Create random id
def pkgen():
    rude = ('lol',)
    bad_pk = True
    while bad_pk:
        pk = b32encode(sha1(str(random())).digest()).lower()[:24]
        bad_pk = False
        for rw in rude:
            if pk.find(rw) >= 0: bad_pk = True
    return pk

# Create your models here.
class User(AbstractUser):
    muhtar = models.BooleanField(null=False,default=False)
    tc = models.CharField(max_length=11, null=False, unique=True)
    address = models.TextField(null=False)
    need_help = models.BooleanField(default=False)
    date_joined = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'tc' #Uyar─▒! Bu benzersiz olmas─▒n─▒ ister
    REQUIRED_FIELDS = ['username']
    def __str__(self):
        return f"{self.username}"

class sos(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    sos_key = models.CharField(max_length=24, primary_key=True, default=pkgen, unique=True)
    address = models.TextField(null=False, unique=False)
    
    def __str__(self):
        return f"{self.user}"

views.py:

from django.shortcuts import render, redirect
from .models import User
from django.contrib.auth import authenticate, login, logout

# Create your views here.
def index(request):
    return render(request, "harita.html")

def register(request):
    if request.method == "POST":
        username = request.POST.get("kullaniciadi")
        email = request.POST.get("email")
        tc = request.POST.get("tc-no")
        password = request.POST.get("password")
        muhtar = request.POST.get("muhtar-check")
        if muhtar == "on":
            muhtar = True
        else:
            muhtar = False
        if username == "" or password == "" or tc == "" or email == "":
            return render(request, "register.html", {"error": "L├╝tfen t├╝m alanlar─▒ doldurun."})
        #elif len(tc) != 11:
        #    return render(request, "register.html", {"error": "TC kimlik numaras─▒ 11 haneli olmal─▒d─▒r."})
        elif User.objects.filter(tc=tc).exists() or User.objects.filter(email=email).exists():
            return render(request, "register.html", {"error": "Bu kimlik numaras─▒ veya e-posta adresi zaten kullan─▒l─▒yor."})
        else:
            user=User.objects.create_user(username=username, email=email, password=password, tc=tc, muhtar=muhtar)
            user.save()
            return redirect("login")
    return render(request, "register.html")

def login(request):
    if request.method == "POST":
        tc = request.POST.get("tc-no")
        password = request.POST.get("password")
        email = request.POST.get("email")
        if tc == "" or password == "" or email == "":
            return render(request, "login.html", {"error": "L├╝tfen t├╝m alanlar─▒ doldurun."})
        user = authenticate(request=request, tc=tc, password=password, email=email)
        print(user)
        if user is not None:
            login(request, user)
            return redirect("index")
        else:
            print(f"""
***************
TC: {tc}
┼×ifre: {password}
E-posta: {email}
***************""")
            return render(request, "login.html", {"error": "E-posta, T.C. veya ┼čifre hatal─▒."})
    return render(request, "login.html")

def logoutPage(request):
    logout(request)
    return render(request, 'logout.html')

def profile(request):
    if request.user.is_authenticated == False:
        return redirect("register")
    else:
        user = User.objects.get(tc=request.user.tc)
        return render(request, "profile.html", {"user": user})

def sos(request):
    if request.user.is_authenticated == False:
        return redirect("register")
    elif not request.user.muhtar:
        return render(request, "harita.html", {"error": "Yard─▒m ├ža─č─▒rma yetkiniz yok."})

    if request.method == "POST":
        malzemeler = request.POST.get("exampleFormControlTextarea1")
        
        if not malzemeler:
            return render(request, "sos.html", {"fillError": "L├╝tfen gerekli alanlar─▒ doldurun."})
        
        # Kullan─▒c─▒n─▒n adresini ve usernamesini alabilirsiniz, ├Ârne─čin:
        adres = request.user.address
        username = request.user.username
        
        # ─░┼člemlerinizi yapabilirsiniz, ├Ârne─čin bu bilgileri bir veritaban─▒na kaydedebilirsiniz.
        
        # Ba┼čar─▒l─▒ bir ┼čekilde i┼člem yap─▒ld─▒─č─▒nda kullan─▒c─▒ya bir mesaj g├Ândermek i├žin
        return render(request, "sos.html", {"succmsg": "Yard─▒m ├ža─čr─▒n─▒z ba┼čar─▒yla g├Ânderildi."})
    
    return render(request, "sos.html")

login.html:

{% load static %}
<!DOCTYPE html>
<html lang="tr">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Giri┼č Sayfas─▒</title>
    <link rel="stylesheet" href="{% static 'libs/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'register_and_login.css' %}">
    <script src="{% static 'libs/jquery.min.js' %}"></script>
</head>

<body>
    {% block navbar %}
        {% include "navbar.html" %}
    {% endblock navbar %}
    <div class="container">
        <br>
        <div id="brs">
            <br><br><br><br>
        </div>
        <!--giri┼č formu-->
        <form id="giris-form" method="POST">
            {% csrf_token %}
            {% if error %}
                <div class="alert alert-danger">{{ error }}</div>
            {% endif %}
            <h3>Giri┼č Yap</h3>

            <label for="email">Email</label>
            <input type="text" id="email" name="email">

            <label for="tc-no">T.C. kimlik numaras─▒</label>
            <input type="text" id="tc-no" name="tc-no">

            <label for="parola">Parola</label>
            <input type="password" id="parola" name="password">

            <button type="submit" id="giris-yap">Giri┼č Yap</button>
        </form>
    </div>
</body>

</html>

IÔÇÖm in a really difficult situation. I need to finish the project urgently and I canÔÇÖt make any progress because of this problem.

There are several errors in your code:

  • your user model declares ÔÇśusernameÔÇÖ as a required field whereas the model does not have such field. self.username used in the __str__ method is likely to fail because this field does not exist.

  • I suppose you use django.contrib.auth.backends.ModelBackend as authentication backend in your settings. If so, the parameters passed to authenticate method should be username and password (not tc and password) : this is the backend which will map the username parameter with the tc field of yhe model based on USERNAME_FIELD value. Changing tc=tc to username=tc in the call to authenticate should solve your issue

1 Like

the first point of view is that the function to register user is very extensive and can be improved in a more optimal way and the second point of view that I observe is in your html, since in the form tag you only have the id and method==ÔÇťPOSTÔÇŁ but the action==" corresponding endpoint" is missing since that is the one that points to the endpoint of your url. I would like to see your urls to see if they are correct and also the error that you comment.

1 Like

Do you know what is the error I have been dealing with for 5 days? On the HTML registration page, I saved the name tag as ÔÇťparolaÔÇŁ, but this is Turkish, but I translated that word into English in request.POST.get(). Since there is no such tag, it returns an empty value. Django encrypts it and saves it to the database. When I enter the real password on the login page, the empty value does not match the hash value and the authenticate function returns None. Dude, IÔÇÖm an idiot and IÔÇÖve been dealing with this for 5 days. I almost quit my software career :D. Thanks!