Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError : 'NoneType' object has no attribute '_meta'

The issue is I overridded the BaseUser to allow visitors to login with Email and Password instead of the Django default Username. Code works fine unless we introduce serializer. If I pass a User object to the User Serializer it gives

AttributeError : 'NoneType' object has no attribute '_meta'

Below are my files:

View.py

class Carrier(APIView):
def post(self, request, format='json'):      #create
    try:
        data = request.data
        print(data['domainID'])
        domain = Domain.objects.get(id = data['domainID'])
        print(domain)
        role   = UserRole.objects.get(id = data['roleID'])
        print(role)

        user_obj = User(
                                                        email       = data['email'],
                                                        domainID    = domain,
                                                        roleID      = role,
                                                        user_name   = data['user_name'],
                                                        phone       = data['phone']
                                                )  

        user_obj.set_password(data['password'])                                              
        user_obj.save()

        carr_obj = CarrierExtraInfo.objects.create(CustomUserID=user_obj,somevalue=data['CustomUserID']['somevalue'])        
        context = {
            "data": data['user_name'],
            "message": 'verify your account'
        }
        carr_obj.save()
        return Response(context, status=status.HTTP_200_OK)
    except Exception as e:
        context = {
            "data": str(e),
            "message": 'invalid details'
        }
        return Response(context,status=status.HTTP_400_BAD_REQUEST)

custom_user model

class User(AbstractBaseUser):
    objects = UserManager()
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )

    domainID    =  models.ForeignKey(Domain, on_delete = models.CASCADE, null=True,blank=True)
    roleID      =  models.ForeignKey(UserRole, on_delete = models.CASCADE, null=True,blank=True)
    user_name   =  models.CharField(max_length = 200,null=True,blank=True) 
    phone       =  models.CharField(max_length = 50,null=True,blank=True)
    is_verified =  models.BooleanField(default=False)
    active      =  models.BooleanField(default=True)
    staff       =  models.BooleanField(default=False) # a admin user; non super-user
    admin       =  models.BooleanField(default=False) # a superuser
    created_DT  =  models.DateTimeField(auto_now_add=True)
    updated_DT  =  models.DateTimeField(auto_now=True)

carrier model

class CarrierExtraInfo(models.Model):
    CustomUserID  = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True)
    somevalue     = models.CharField(max_length=100,null=True,blank=True)
    is_active     = models.BooleanField(default=True)


    created_DT    = models.DateTimeField(auto_now_add=True)
    updated_DT    = models.DateTimeField(auto_now=True)

custom_user serializer

class CreateCarrierSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email','domainID','roleID','user_name','phone')

carrier serializer

class CarrierExtraInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = CarrierExtraInfo
        exclude = ('created_DT','updated_DT')

output error

File "E:\KargoLogic\venv\lib\site-packages\rest_framework\serializers.py", line 370, in _writable_fields
  field for field in self.fields.values() if not field.read_only 
File "E:\KargoLogic\venv\lib\site-packages\rest_framework\serializers.py", line 363, in fields
  for key, value in self.get_fields().items(): 
File "E:\KargoLogic\venv\lib\site-packages\rest_framework\serializers.py", line 1024, in get_fields
  info = model_meta.get_field_info(model) 
File "E:\KargoLogic\venv\lib\site-packages\rest_framework\utils\model_meta.py", line 39, in get_field_info
  forward_relations = _get_forward_relationships(opts) 
File "E:\KargoLogic\venv\lib\site-packages\rest_framework\utils\model_meta.py", line 96, in _get_forward_relationships
  not field.remote_field.through._meta.auto_created
AttributeError: 'NoneType' object has no attribute '_meta'

"POST /carr/api/carr_user HTTP/1.1" 500 16718

why i'm getting this? On migration there is no error, but on POST request this error arrives.

like image 500
kritesh Avatar asked Feb 14 '19 05:02

kritesh


2 Answers

When you have a custom Django User model make sure you are importing it correctly in files that initiate User (From the Django Docs). So, add the following to the top of your serializers.py file. This fixed the same error for me.

from django.contrib.auth import get_user_model

User = get_user_model()
like image 164
mcmenemy Avatar answered Nov 14 '22 22:11

mcmenemy


Not Indented Properly

class CreateCarrierSerializer(serializers.ModelSerializer):
     class Meta:
        model = User
        fields = ('email','domainID','roleID','user_name','phone')
like image 22
Clifton Avil D'Souza Avatar answered Nov 14 '22 23:11

Clifton Avil D'Souza