How to authenticate user form credentials from PostgreSQL with Django

I am able to register users to my custom table in the Postgres database. I would like to know how can I use the credentials from my Postgres table to authenticate login from my django web app. I know I have to create a custom backend but I don't know how we can import the credentials from Postgres to authenticate against the credentials that user entered.

My model:

from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractBaseUser

# Create your models here.

# Database model Users has one to one relationship with Django User table
from django.db.models.signals import post_save
from django.dispatch import receiver


class Profile(AbstractBaseUser):

    first_name = models.TextField()
    last_name = models.TextField()
    user = models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    user_name = models.TextField(unique=True)
    email = models.TextField()
    password1 = models.TextField()
    password2 = models.TextField()
    date_created = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'user_name'
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.user.username

    @receiver(post_save, sender=User)
    def update_profile_signal(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)
        instance.profile.save()

I have my django project pointing towards my custom user model too.

I just don't know how to create a custom backend for authentication. If I could be guided towards it, I would really appreciate.

If you set the password for each user when creating a new user, the default authentication backend for Django will work just fine for you. When saving a new Profile you should just do a instance.set_password(password) after validating if password and password2 are the same.

Also I would recommend not using receiver but rather maintaining a CustomManager for your table.

For now this should do the trick for you:

@receiver(post_save, sender=User)
    def update_profile_signal(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)
        if password == password2:
            instance.set_password(password)
        instance.profile.save()

Then you can limit access to Views using the @login_required decorator. Some other ways are mentioned here

Back to Top