Django用户模型AttributeError:'str'对象没有属性'objects'

hackingtech主页

我正在使用django作为项目的后端,但是每当我在User模型上执行查询时,都会收到错误消息 AttributeError: 'str' object has no attribute 'objects'

但是仅当我从设置导入用户模型时才会出现此错误

from django.conf import settings
User = settings.AUTH_USER_MODEL

但不是来自 from django.contrib.auth.models import User

Settings.py

AUTH_USER_MODEL = 'users.User'

用户的Models.py

from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from rest_framework.authtoken.models import Token


class UserManager(BaseUserManager):
    def create_user(self, email,username, password, phone, **extra_fields):
        if not email:
            raise ValueError("Email Address Is Needed")
        if not username:
            raise ValueError("Username Must Be Provided")

        email = self.normalize_email(email)
        user = self.model(
            email=email,
            username=username,
            phone=phone
        )
        user.set_password(password)
        user.is_active = False
        user.save()

    def create_superuser(self, email,username, password,phone):
        email = self.normalize_email(email)
        user = self.model(
            email=email,
            username=username,
            phone=phone
        )
        user.set_password(password)
        user.is_active = True
        user.is_admin = True
        user.save()


class User (AbstractBaseUser):
    username = models.CharField(max_length=254,blank=False,null=False,unique=True)
    email = models.EmailField(
        unique=True, max_length=254, blank=False, null=False)
    phone = models.CharField(max_length=250,blank=False,null=False,unique=True)
    is_active = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email','phone']

    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin


Views.py


User = settings.AUTH_USER_MODEL
response = {}
class RegisterUserView(APIView):
    def post(self,request,**kwargs):
        username = self.request.POST['username']
        email = self.request.POST['email']
        phone = self.request.POST['phone']
        password = self.request.POST['password']
        password2 = self.request.POST['password2']

        if username:
            if User.objects.filter(username=username).exists():
                response['message'] = "Username Already Exists"
                return Response(response)

        if email:
            if User.objects.filter(email=email).exists():
                response['message'] = 'Email Already Exists'
                return Response(response)
        if phone:
            if User.objects.filter(phone=phone).exists():
                response['message'] = 'Phone Number Already Exists'
                return Response(response)
        if password and password2:
            if password != password2:
                response['message'] = 'Password Does Not Match'
                return Response(response)

        if "".strip() in (username,email,password,password2,phone):
            response['message'] = 'Some Credentials Were Invalid'
            return Response(response)

        # user = User.objects.create(username=username,email=email,phone=phone,password=password2)
        # user.save()
        response['status'] = 'Created'
        return Response(response)

完整错误回溯

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/lib/python3/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/freduah/.local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/freduah/.local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/freduah/.local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/freduah/.local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/freduah/VideoCallDesign/learning/learningDatabase/users/views.py", line 47, in post
    if User.objects.filter(username=username).exists():
AttributeError: 'str' object has no attribute 'objects'
汤姆·沃西克

好,

AUTH_USER_MODEL = 'users.User'

确实是一个字符串。

所以当你说

但是仅当我从设置导入用户模型时才会出现此错误

您不正确,因为您不User以此方式导入模型。

使用get_user_model代替它使用它AUTH_USER_MODEL来返回User模型。如果您想了解其实际发生方式,请查看源代码

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

/'str'对象的AttributeError没有属性'objects'

“str”对象没有属性“objects”django

Stripe AttributeError: 'str' 对象没有属性 'objects'(自定义用户模型)

Django -AttributeError:“ str”对象没有属性“ objects”

AttributeError:'str'对象没有属性'str'

AttributeError:“ str”对象没有属性“ name”

AttributeError:'str'对象没有属性'errno'

AttributeError:'str'对象没有属性'union'

AttributeError: 'str' 对象没有属性 'loc'

AttributeError:“ str”对象没有属性“ ndim”

AttributeError:“ str”对象没有属性“ values”

AttributeError:'str'对象没有属性'xpath'

AttributeError:“ str”对象没有属性“ decode”

AttributeError(“'str'对象没有属性'read'”)

AttributeError(“'str'对象没有属性'read'”)

AttributeError: 'str' 对象没有属性 'fetchone'

AttributeError:'str'对象没有属性'isnumeric'

AttributeError: 'str' 对象没有属性 'client'

AttributeError:'str'对象没有属性'fileno'

AttributeError: 'str' 对象没有属性 'keys'

AttributeError:'str'对象没有属性sleep

attributeError:'str'对象没有属性'dbname'

AttributeError: 'str' 对象没有属性 'map'

AttributeError:'str'对象没有属性'author'

AttributeError: 'str' 对象没有属性 'mode'

AttributeError: 'str' 对象没有属性 'execute'

AttributeError:'str'对象没有属性'description'

AttributeError:“ str”对象没有属性“ float”

AttributeError'str'对象没有属性'path'