IntegerField with choices and null

1,390 views
Skip to first unread message

Milorad Pop-Tosic

unread,
Jun 28, 2013, 9:36:58 AM6/28/13
to django-res...@googlegroups.com
Hello,

I have a Django model with IntegerField with choices, and null=True, blank=True. I've written a simple
CreateAPIView and a serializer for the modelI haven't overriden any fields in the serializer.

The only issue I'm having is when I'm adding objects by using the form in the API browser and I leave
the choices field blank (the form correctly displays the blank option). I get the following exception:

invalid literal for int() with base 10: ''

I've tried overriding the field in the serializer with ChoiceField from Django Rest Framework and
setting required=False, but this doesn't work either.

Since everything works fine when I use the API with JSON, this is a minor issue, but I'd like to
know why it isn't working as expected.

Thanks in advance,
Milorad

Joseph Wayodi

unread,
Jul 30, 2013, 11:50:00 AM7/30/13
to django-res...@googlegroups.com
Hello,

I also just came across this issue.

My current workaround is, in my Django REST framework model viewset subclass, I check the object for the Django model integer fields that are optional, and that have the value "" (set by the Django REST framework's serializer choice field on an empty selection), and then set them back to None, as required. Below is the code snippet:

from django.db.models.fields import IntegerField
from rest_framework import viewsets
class BaseModelMixin(viewsets.ModelViewSet):
    def pre_save(self, obj):
        super(BaseModelMixin, self).pre_save(obj)
        for field in obj._meta.fields:
            if isinstance(field, IntegerField) and field.null and field.blank and getattr(obj, field.name) == '':
                setattr(obj, field.name, None)

Does anyone have a better way of doing it?

Regards,

Joseph.
Reply all
Reply to author
Forward
0 new messages