使用自定义mysql表连接用户模型

时间:2020-02-20 03:58:09

标签: mysql django django-models django-rest-framework django-authentication

我正在尝试从this tutorial实施Django身份验证。

这是我的模型的内容。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')

身份验证系统正在运行,但是问题是我现在想使用现有的mysql usertable 更改用户模型后端。

这是用户表的表结构:

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;

有没有办法在不破坏认证方案的情况下以最少的重构工作量完成现有代码库?

1 个答案:

答案 0 :(得分:1)

您正在寻找db_table模型选项。这是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)

通常,id是一个自动字段,它是主键并自动递增。我不认为user_id是那样。由您决定将id定义为autofield并覆盖为db_column=user_id