django 无此表:API_user

4bbkushb  于 2023-06-30  发布在  Go
关注(0)|答案(1)|浏览(112)

我以前使用from django.contrib.auth.models import User,但现在我需要切换到AbstractUser。如何将数据从上一个auth_user表传输到AbstractUser?我跟着code from here
models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    username = models.CharField(max_length=50, unique=True)
    email = models.CharField(max_length=100)
    password = models.CharField(max_length=100)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

serializers.py

from .models import User
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'email', 'password']
        extra_kwargs = {
            'password': {'write_only': True} # Don't return password
        }

    def create(self, validated_data): # Hash password
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

当我登录到管理页面时,我得到:
无此类记录:API_user
我想在不删除auth_user表的情况下使用AbstractUser

7lrncoxx

7lrncoxx1#

请按照以下步骤操作:

  • 在settings.py中设置AUTH_USER_MODEL = 'users.User'
  • 删除“迁移”文件夹。
  • 删除“db.sqlite3”文件。
  • 运行python manage.py makemigrations your_appname
  • 运行python manage.py migrate
  • 运行python manage.py createsuperuser

相关问题