Pre-save method not being called on ModelViewSet

Showing 1-4 of 4 messages
Pre-save method not being called on ModelViewSet thongly 6/4/13 1:56 PM
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!!!'



Re: Pre-save method not being called on ModelViewSet thongly 6/4/13 2:00 PM
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.
Re: Pre-save method not being called on ModelViewSet thongly 6/4/13 2:20 PM
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.
Re: Pre-save method not being called on ModelViewSet thongly 6/4/13 10:18 PM
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.