Django Forms with Nested Serializer - Validation Issues When Using Multiple Embedded Models
I'm working through a tutorial and I'm working on a Django application where I need to handle a form submission that includes nested serializers for related models... Specifically, I'm using Django REST Framework and I have a `Book` model that has a one-to-many relationship with a `Chapter` model. When I submit the data through my API, I get a validation behavior that doesn't seem to provide enough context about what went wrong. Here's the structure of my models: ```python class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) class Chapter(models.Model): title = models.CharField(max_length=100) book = models.ForeignKey(Book, related_name='chapters', on_delete=models.CASCADE) ``` I want to create or update a `Book` along with its `Chapters`. My serializers look like this: ```python from rest_framework import serializers class ChapterSerializer(serializers.ModelSerializer): class Meta: model = Chapter fields = ['title'] class BookSerializer(serializers.ModelSerializer): chapters = ChapterSerializer(many=True) class Meta: model = Book fields = ['title', 'author', 'chapters'] def create(self, validated_data): chapters_data = validated_data.pop('chapters') book = Book.objects.create(**validated_data) for chapter_data in chapters_data: Chapter.objects.create(book=book, **chapter_data) return book ``` The question arises when I send a payload like this: ```json { "title": "My Book", "author": "John Doe", "chapters": [ {"title": "Introduction"}, {"title": "Chapter 1"} ] } ``` The API responds with a 400 status and the behavior message: ``` { "chapters":[ { "non_field_errors":[ "This field may not be null." ] } ] } ``` I suspect it has something to do with how I'm handling the nested `ChapterSerializer`, but I'm not sure what I've missed. I've made sure that the `validated_data` contains the chapters, yet I still get this behavior. I've also tried adjusting the `create` method to explicitly check for the presence of `chapters_data`, but the behavior continues. Could someone guide to understand how to properly validate the nested data in this scenario or point out what could be causing this scenario? I'm using Django 3.2 and Django REST Framework 3.12. My development environment is Ubuntu 22.04. Is there a better approach?