Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework - save a formset?

Is there a way to save a formset elegantly? I tried pushing all data into serializer but its validated_data is empty and so nothing gets created:

This is the formset data as is comes:

enter image description here

each object is this serializer:

class RAGReportAtomSerializer(serializers.ModelSerializer):
    marker = RAGMarkerSerializer()
    item = RAGItemsSerializer()

    class Meta:
        model = RAGReportAtom
        fields = (
            'id',
            'item',
            'marker',
            'comments'
        )

class RAGMarkerSerializer(serializers.ModelSerializer):
    class Meta:
        model = DicRAGMarker
        fields = (
            'name',
            'color_code',
            'icon'
        )


class RAGItemsSerializer(serializers.ModelSerializer):
    class Meta:
        model = DicRAGItem
        fields = (
            'name',
            'description',
        )

I am trying to save it like this:

def create(self, request, project_id):
        serialized_data = RAGReportAtomSerializer(data=request.DATA, many=True)
        if serialized_data.is_valid():
            serialized_data.save()
            msg = MessageSerializer(Message(title='OK', body="Milestone successfully created!"))
            return Response(msg.data, status=HTTP_201_CREATED)
        else:
            return Response(serialized_data.errors, status=HTTP_400_BAD_REQUEST)
like image 865
abolotnov Avatar asked Jun 05 '26 04:06

abolotnov


1 Answers

I have made a little thing that does the job but it doesn't fix the thing though. Just in case this could help someone.

    data = {}
    for item in request.DATA:
        match = re.match("^form-(\d)-(.+)", item)
        if match:
            match_form = match.group(1)
            match_key = match.group(2)
            if not data.get(match_form, None):
                data[match_form] = {}
            data[match_form][match_key] = request.DATA[item]

    for item in data:
        serialized_data = RAGReportAtomBaseSerializer(data=data[item])
like image 172
abolotnov Avatar answered Jun 07 '26 23:06

abolotnov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!