我以前使用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
。
1条答案
按热度按时间7lrncoxx1#
请按照以下步骤操作:
AUTH_USER_MODEL = 'users.User'
。python manage.py makemigrations your_appname
。python manage.py migrate
。python manage.py createsuperuser
。