Connect user model with custom mysql table

light42 :

I was trying to implement django authentication from this tutorial.

This is the content of my models.py:

import jwt

from datetime import datetime, timedelta

from django.conf import settings
from django.contrib.auth.models import (
     AbstractBaseUser, BaseUserManager, PermissionsMixin
)
from django.db import models

# Create your models here.

class UserManager(BaseUserManager):
  def create_user(self, username, email, password=None):
      if username is None:
         raise TypeError('Users must have a username.')

      if email is None:
         raise TypeError('Users must have an email address.')

      user = self.model(username=username, email=self.normalize_email(email))
      user.set_password(password)
      user.save()

      return user

  def create_superuser(self, username, email, password):
      if password is None:
         raise TypeError('Superusers must have a password.')

      user = self.create_user(username, email, password)
      user.is_superuser = True
      user.is_staff = True
      user.save()

      return user

class User(AbstractBaseUser, PermissionsMixin):
  username = models.CharField(db_index=True, max_length=255, unique=True)

  email = models.EmailField(db_index=True, unique=True)

  is_active = models.BooleanField(default=True)

  is_staff = models.BooleanField(default=False)

  created_at = models.DateTimeField(auto_now_add=True)

  updated_at = models.DateTimeField(auto_now=True)

  USERNAME_FIELD = 'email'
  REQUIRED_FIELDS = ['username']

  objects = UserManager()

  def __str__(self):
      return self.username

  @property
  def token(self):
      return self._generate_jwt_token()

  def get_full_name(self):
      return self.username

  def get_short_name(self):
      return self.username

  def _generate_jwt_token(self):
      dt = datetime.now() + timedelta(days=60)

      token = jwt.encode({
          'id': self.pk,
          'exp': int(dt.strftime('%s'))
      }, settings.SECRET_KEY, algorithm='HS256')

      return token.decode('utf-8')

The authentication system is working, but the problem is now I want to change the user model backend with existing mysql usertable.

Here's usertable's table structure:

CREATE TABLE `usertable` (
 `user_id` int(100) NOT NULL,
 `username` varchar(50) NOT NULL,
 `nama` varchar(100) NOT NULL,
 `email` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Is there a way to make it done with the least amount of refactoring effort to existing codebase without breaking the authentication scheme?

schillingt :

You're looking for the db_table model option. Here are the docs.

class User(AbstractBaseUser, PermissionsMixin):
    class Meta:
        db_table = 'usertable'
    username = models.CharField(db_index=True, max_length=255, unique=True) # The varchar length and this length are different. I suggest modifying the table.
    email = models.EmailField(db_index=True, unique=True) # The varchar length and this length are different. I suggest modifying the table.
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    nama = models.CharField(max_length=100, null=False)

Typically the id is an auto field that's a primary key and auto-incrementing. I don't think user_id is that. It's up to you to define and override id as an autofield with db_column=user_id.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11859&siteId=1