class UpdateModelMixin

from rest_framework.mixins import UpdateModelMixin
Documentation Source code
    Update a model instance.
    Should be mixed in with `SingleObjectBaseView`.
    

Ancestors (MRO)

  1. UpdateModelMixin

Methods used but not implemented in this class

  • get_slug_field
  • get_serializer
  • get_object
Expand Collapse

Methods

def pre_save(self, obj): UpdateModelMixin

        Set any attributes on the object that are implicit in the request.
        
    def pre_save(self, obj):
        """
        Set any attributes on the object that are implicit in the request.
        """
        # pk and/or slug attributes are implicit in the URL.
        pk = self.kwargs.get(self.pk_url_kwarg, None)
        if pk:
            setattr(obj, 'pk', pk)

        slug = self.kwargs.get(self.slug_url_kwarg, None)
        if slug:
            slug_field = self.get_slug_field()
            setattr(obj, slug_field, slug)

        # Ensure we clean the attributes so that we don't eg return integer
        # pk using a string representation, as provided by the url conf kwarg.
        if hasattr(obj, 'full_clean'):
            obj.full_clean()

def update(self, request, *args, **kwargs): UpdateModelMixin

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        try:
            self.object = self.get_object()
            success_status_code = status.HTTP_200_OK
        except Http404:
            self.object = None
            success_status_code = status.HTTP_201_CREATED

        serializer = self.get_serializer(self.object, data=request.DATA,
                                         files=request.FILES, partial=partial)

        if serializer.is_valid():
            self.pre_save(serializer.object)
            self.object = serializer.save()
            return Response(serializer.data, status=success_status_code)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)