python - 在 Django 中创建用户时出现以下错误 : type object 'User' has no attribute 'objects'

标签 python django authentication createuser

我已经编写了一个 View 来为我的应用程序注册新用户,但是当我尝试运行它时,出现错误:

type object 'User' has no attribute 'objects'

我的代码如下所示:

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core import serializers

from rest_framework.views import APIView
from rest_framework.response import Response

from users.serializers import *

class Register(APIView):

    def post(self, request):
        serialized = UserSerializer(data=request.DATA)
        if serialized.is_valid():
            user = User.objects.create_user(serialized.init_data['email'], serialized.init_data['username'], serialized.init_data['password'])
            return Response(serialized.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

编辑: 我的 user.serializers 模块如下所示:

from django.forms import widgets
from rest_framework import serializers
from django.contrib.auth import get_user_model

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ('date_joined','email','first_name','id','last_login','last_name','username')

最佳答案

如果您无论如何都要创建一个 CustomUserCustomAccountManager

class CustomAccountManager(BaseUserManager):
     ......
     .....
     ...
class CustomUser(AbstractBaseUser, PermissionsMixin):
     ......

      # make sure it is [objects] and not [object]

      objects = CustomAccountManager()

     ....
     ...

关于python - 在 Django 中创建用户时出现以下错误 : type object 'User' has no attribute 'objects' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23107839/

相关文章:

Django:在模型选择中结合使用惰性翻译和标记安全

带有 docker-compose 的 Django 应用程序将数据保存在媒体卷中

ruby-on-rails - 让 Devise 识别我的身份验证模块

python - 我怎样才能通过一个函数保存我的参数值,以便它可以使用它的初始值多次使用?

python - 自定义 python-levenshtein 字符值

当用户同时编辑时,Django 内联表单集抛出 IndexError

javascript - NodeJS + Ajax + 登录表单

authentication - 远程图像嵌入 : how to handle ones that require authentication?

python - 在 Python 中求和 Counter 对象的有效方法

python - 计算两个字符串之间的差异