I want to edit a django-rest-framwork
serializer object before it is saved. This is how I currently do it -
def upload(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid(): # All validation rules pass
obj = form.save(commit=False)
obj.user_id = 15
obj.save()
How can I do it with a django-rest-framework
serializer object?
@api_view(['POST','GET'])
def upload_serializers(request):
if request.method == 'POST':
serializer = FilesSerializer(data=request.DATA, files=request.FILES)
if serializer.is_valid():
serializer.save()
You can edit the serializer's object before save the serializer:
Now edited for REST framework 3
With REST framework 3 the pattern is now:
Note that the serializers do not now ever expose an unsaved object instance as
serializer.object
, however you can inspect the raw validated data asserializer.validated_data
.If you're using the generic views and you want to modify the save behavior you can use the
perform_create
and/orperform_update
hooks...