0

I am using django as my backend for a project but anytime i perform queries on my User model, i get the error AttributeError: 'str' object has no attribute 'objects'

But this error only occurs when i import the user model from settings

from django.conf import settings
User = settings.AUTH_USER_MODEL

but not from from django.contrib.auth.models import User

Settings.py

AUTH_USER_MODEL = 'users.User'

User's 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)

Full Error Traceback

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'

1 Answer 1

3

Well,

AUTH_USER_MODEL = 'users.User'

indeed is a string.

So when you say

But this error only occurs when i import the user model from settings

You are not correct as you don't import User model this way.

Use get_user_model instead which uses this AUTH_USER_MODEL to return User model. Look at the source if you want to learn how it actually happens.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank You Very Much For The Heads Up. I appreciate. It worked for me
If so, please accept this answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.