DRF:自定义抽象用户后仍需要用户名

时间:2019-10-15 11:14:47

标签: python django django-rest-framework

我正在尝试使用Django和DRF编写REST API。我正在尝试创建一个用户模型并在我的应用程序中使用它。但是问题在于它返回了400错误状态代码,内容为:

  

{“用户名”:[“此字段为必填。”]}

这是我的模型代码:

import uuid

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.conf import settings
from django.dispatch import receiver
from django.utils.encoding import python_2_unicode_compatible
from django.db.models.signals import post_save
from rest_framework.authtoken.models import Token
from api.fileupload.models import File


@python_2_unicode_compatible
class User(AbstractUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    email = models.EmailField('Email address', unique=True)
    name = models.CharField('Name', default='', max_length=255)
    phone_no = models.CharField('Phone Number', max_length=255, unique=True)
    address = models.CharField('Address', default='', max_length=255)
    country = models.CharField('Country', default='', max_length=255)
    pincode = models.CharField('Pincode', default='', max_length=255)
    USERNAME_FIELD = 'email'

    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

序列化器:

class CreateUserSerializer(serializers.ModelSerializer):
    username = None

    def create(self, validated_data):
        validated_data['username'] = uuid.uuid4()
        user = User.objects.create_user(**validated_data)
        return user


    def update(self, instance, validated_data):
        instance.name = validated_data.get('name', instance.name)
        instance.address = validated_data.get('address', instance.address)
        instance.country = validated_data.get('country', instance.country)
        instance.pincode = validated_data.get('pincode', instance.pincode)
        instance.phone_no = validated_data.get('phone_no', instance.phone_no)
        instance.email = validated_data.get('email', instance.email)
        instance.save()
        return instance

    class Meta:
        unique_together = ('email',)
        model = User
        fields = (
            'id', 'password', 'email', 'name', 'phone_no', 'address', 'country', 'pincode',      
        )
        extra_kwargs = {'password': {'write_only': True}}

Admin.py文件:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User


@admin.register(User)
class UserAdmin(UserAdmin):
    pass

2 个答案:

答案 0 :(得分:1)

  

类用户(AbstractUser):

当您的User模型继承自AbstractUser时,它将继承 username字段。

只需通过如下设置usernameUser模型中删除username = None字段:

class User(AbstractUser):
    # ...
    username = None
    # ...

  

UserAdmin(UserAdmin)类:

当您的UserAdmin模型继承自django.contrib.auth.admin.UserAdmin时,您将需要更新fieldsetslist_displaysearch_fieldsordering字段您的UserAdmin模型,因为它们使用的是username,而您已将其从User模型中删除。

答案 1 :(得分:0)

摘要用户始终具有用户名字段。删除它会引起问题。我建议您也将用户的电子邮件地址存储在用户名字段中,并使用它。请确保在两个字段中始终对其进行更新,这不是很难。