Search code examples
pythondjangoauthenticationcreateuser

Get following error when creating user in Django: type object 'User' has no attribute 'objects'


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

Solution

  • 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.