Question

I have written a view to register a new user for my app but when I try running it, I get the error:

type object 'User' has no attribute 'objects'

My code looks as follows:

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)

Edit: My user.serializers module looks as follows:

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')
Was it helpful?

Solution 3

Okay, I've fixed it, but I think the error has arisen from some issue with my environment setup. I have nevertheless found a way around it. I replaced the following line:

user = User.objects.create_user(serialized.init_data['email'], serialized.init_data['username'], serialized.init_data['password'])

with:

user = get_user_model().objects.create_user(serialized.init_data['username'], email=serialized.init_data['email'], password=serialized.init_data['password'])

I obviously also had to import:

 from django.contrib.auth import get_user_model

I haven't figured out why I needed to use get_user_model() instead of just being able to use my User object directly, but this solved my problem.

OTHER TIPS

If you are in any case making a CustomUser and a CustomAccountManager

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

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

      objects = CustomAccountManager()

     ....
     ...

Do you have a class named User in your serializers module? You're doing from users.serializers import * which will import everything in that module into the current namespace, overriding any names you've already imported. That syntax is usually a bad idea for exactly that reason

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top