[Fixed]-Django Rest Framework: "Invalid literal for in()" with a CharField

1👍

Here you have a CharField:

type = serializers.CharField(source='content_type')

While content_type is a ForeignKey to ContentType which primary key is an integer:

content_type = models.ForeignKey(ContentType)

If you POST type=track, Django will try to cast 'track' as an integer, which obviously fails.

Your type should be:

type = serializers.IntegerField(source='content_type')

And you should not POST type=track, but type=5 for instance if the id of the ContentType row is 5.

Try this on a shell to get the IDs of your content types:

>>> from django.contrib.contenttypes.models import ContentType
>>> ContentType.objects.all().values_list()
[
    (1, 'auth', 'user'),
    (2, 'auth', 'permission'),
    (3, 'auth', 'group'),
    (4, 'contenttypes', 'contenttype'),
    (5, 'sessions', 'session'),
    ...
    (8, 'yourapp', 'yourmodel'),
    ...
]

Leave a comment