Django rest framework how to serialize a list of strings?

Viewed 3873

I want to give a list of strings in postman, for example:

['string1', 'string2', 'string3', 'string4', 'string5']

But when it reaches serializer.is_valid() it gives me:

"non_field_errors": [
            "Invalid data. Expected a dictionary, but got str."
        ]

This is my serializer:

class URLRequestedSerializer(serializers.Serializer):
    urls = serializers.ListField(child=serializers.CharField())

How can I make the serializer to except a list of strings?

2 Answers

It looks like you posted a list instead of a dictionary as JSON in Postman, just as the error message said.

You posted:

['string1', 'string2', 'string3', 'string4', 'string5']

But you should have posted:

{
    "urls": ["string1", "string2", "string3", "string4", "string5"]
}

Remember, your serializer defined the field urls, you therefore have to send the data to the correct field in your JSON body :)

The string list received from postman is string type in django, try to use eval to convert it.

Related