Pre-save method not being called on ModelViewSet

1,190 views
Skip to first unread message

thongly

unread,
Jun 4, 2013, 4:56:59 PM6/4/13
to django-res...@googlegroups.com
I am posting to the DefaultRouter create via a Form. I have excluded a "created_by" field from my form, hoping to populate it via the pre_save method. However, the ModelViewSet does not seem to call it.

400: "{"created_by": ["This field is required."]}"


class MyModelViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = MyModel.objects.all() serializer_class = MyModelSerializer paginate_by = 5 parser_classes = ( parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser, ) def pre_save(self, obj): print 'START PRESAVE!!!' obj.slug = slugify(obj.title) obj.created_by = self.request.user print 'PRESAVE END!!!'



thongly

unread,
Jun 4, 2013, 5:00:37 PM6/4/13
to django-res...@googlegroups.com
It just occurred to me that the serializer is being validated first. Therefore, it might be a requirement to explicitly set a required=False on the serializer even though this is a ModelSerializer.

I will try this and reply here.

thongly

unread,
Jun 4, 2013, 5:20:01 PM6/4/13
to django-res...@googlegroups.com
After setting required=False for the "created_by" field on the serializer, the error returned is now:

500: ValueError: Cannot assign None: "MyModel.created_by" does not allow null values

My model does in fact require this value. I was trying to account for this i pre-save. Any help would be appreciated.

thongly

unread,
Jun 5, 2013, 1:18:16 AM6/5/13
to django-res...@googlegroups.com
To Tom or whoever of the maintainers ends up reading this:

The solution was to simply exclude the "created_by" field from the serializer - required=False did not sufficient - and then pre-save repopulates the created_by.

class MyModelSerializer(serializers.ModelSerializer):
       # created_by = serializers.SlugRelatedField(slug_field='username', required=False) <--- This will NOT work

class Meta:
model = MyModel
exclude = ('created_by',) # <---- This is the key



However, I'm unsure why required=False in the field will not work, and whether this is a bug.
Reply all
Reply to author
Forward
0 new messages