DEV Community

Moin Ul Haq
Moin Ul Haq

Posted on

Fixing “Got AttributeError: 'NoneType' object has no attribute …” in Django REST Framework

Hi! I’m Moin Ul Haq, a Software Engineer from Bahawalpur specializing in Django backend development.

If you’ve ever worked with Django REST Framework (DRF), you may have seen this frustrating error:
AttributeError: 'NoneType' object has no attribute 'id'

This usually happens when Serializer.save() or a nested serializer tries to access a field that doesn’t exist or is not properly passed.

In this tutorial, I’ll show you:

  • Why this error occurs
  • How to reproduce it
  • How to fix it cleanly in DRF

By the end, your serializers will handle missing data safely, and this error will become a thing of the past.

Step 1: Understanding the Error

This error typically occurs in DRF when:

  • A nested serializer expects a related object but receives None
  • A required field is missing in validated_data
  • You call .id or access attributes on a NoneType object

Example scenario:

from rest_framework import serializers
from .models import Task, Project

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ['id', 'title', 'project']

    def create(self, validated_data):
        project = validated_data.get('project')
        print(project.id)  # ❌ Error occurs here if project is None
        return Task.objects.create(**validated_data)
Enter fullscreen mode Exit fullscreen mode

If a client POSTs without project, DRF will raise:
AttributeError: 'NoneType' object has no attribute 'id'

Step 2: Proper Validation in Serializer

The clean way to fix this is to validate the field before using it:

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ['id', 'title', 'project']

    def create(self, validated_data):
        project = validated_data.get('project')
        if project is None:
            raise serializers.ValidationError({
                'project': 'Project must be provided.'
            })
        return Task.objects.create(**validated_data)

Enter fullscreen mode Exit fullscreen mode

✅ Now, if the client forgets project, they get a clear DRF validation error instead of AttributeError.

Step 3: Optional Nested Objects

Sometimes, the field may be optional. In that case, handle it like this:

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ['id', 'title', 'project']

    def create(self, validated_data):
        project = validated_data.get('project')
        task = Task.objects.create(
            title=validated_data.get('title'),
            project=project if project else None
        )
        return task
Enter fullscreen mode Exit fullscreen mode
  • If project is missing, the serializer still works
  • No more “NoneType object has no attribute …” error

Step 4: Always Test Your API

Example POST request:
{
"title": "Finish DRF Tutorial"
}

  • With validation: returns 400 Bad Request with message: "Project must be provided."
  • Without validation: crashes with AttributeError

✅ This ensures clean error handling and a better developer experience.

Conclusion

The “Got AttributeError: 'NoneType' object has no attribute …” error is one of the most common issues in Django REST Framework, especially for beginners dealing with nested serializers or required fields.

Key takeaways:

  • Always validate required fields before accessing attributes
  • Use serializers.ValidationError for meaningful messages
  • Optional fields should be handled with None checks

About the Author

I’m Moin Ul Haq, a Software Engineer from Bahawalpur specializing in Django & Python backend development. I share tutorials, tips, and real-world solutions to help developers build scalable web applications.

Follow me on Dev.to or check my GitHub: moin-ul-haq
for more backend projects.

Top comments (0)