Python rest_framework.status.HTTP_204_NO_CONTENT Examples

The following are 30 code examples for showing how to use rest_framework.status.HTTP_204_NO_CONTENT(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.status , or try the search function .

Example 1
Project: django-puppy-store   Author: realpython   File: views.py    License: MIT License 7 votes vote down vote up
def get_delete_update_puppy(request, pk):
    try:
        puppy = Puppy.objects.get(pk=pk)
    except Puppy.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    # get details of a single puppy
    if request.method == 'GET':
        serializer = PuppySerializer(puppy)
        return Response(serializer.data)

    # update details of a single puppy
    if request.method == 'PUT':
        serializer = PuppySerializer(puppy, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    # delete a single puppy
    if request.method == 'DELETE':
        puppy.delete()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 2
Project: controller   Author: deis   File: views.py    License: MIT License 6 votes vote down vote up
def destroy(self, request, **kwargs):
        calling_obj = self.get_object()
        target_obj = calling_obj

        if request.data.get('username'):
            # if you "accidentally" target yourself, that should be fine
            if calling_obj.username == request.data['username'] or calling_obj.is_superuser:
                target_obj = get_object_or_404(User, username=request.data['username'])
            else:
                raise PermissionDenied()

        # A user can not be removed without apps changing ownership first
        if len(models.App.objects.filter(owner=target_obj)) > 0:
            msg = '{} still has applications assigned. Delete or transfer ownership'.format(str(target_obj))  # noqa
            raise AlreadyExists(msg)

        try:
            target_obj.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except ProtectedError as e:
            raise AlreadyExists(e) 
Example 3
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def add_user(self, request, pk=None):
        group = self.get_object()

        if not request.data.get("user_id"):
            return Response(
                {"user_id": "This field is required."}, status=status.HTTP_400_BAD_REQUEST
            )

        try:
            user = User.objects.get(pk=request.data.get("user_id"))
        except User.DoesNotExist:
            return Response({"user_id": "Invalid user ID."}, status=status.HTTP_400_BAD_REQUEST)

        if request.user == user:
            return Response(status=status.HTTP_403_FORBIDDEN)

        user.groups.add(group)

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 4
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def remove_user(self, request, pk=None):
        group = self.get_object()

        if not request.data.get("user_id"):
            return Response(
                {"user_id": "This field is required."}, status=status.HTTP_400_BAD_REQUEST
            )

        try:
            user = User.objects.get(pk=request.data.get("user_id"))
        except User.DoesNotExist:
            return Response({"user_id": "Invalid user ID."}, status=status.HTTP_400_BAD_REQUEST)

        if user.groups.filter(pk=group.pk).count() == 0:
            return Response(
                {"user_id": "User is not in group."}, status=status.HTTP_400_BAD_REQUEST
            )

        user.groups.remove(group)

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 5
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def destroy(self, request, *args, **kwargs):
        """
        Destroy an image instance.
        """
        image = self.get_object()

        logger.info("user %s deletes image: %s/%s:%s" % (
            request.user.username,
            image.user.username,
            image.name,
            image.version))

        destroyer = ImageDestroyer(image)
        destroyer.destroy_image_instance()

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 6
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def destroy(self, request, *args, **kwargs):
        """
        Destroy volume metadata and instance.
        """
        volume = self.get_object()

        # Check whether project is corresponding to the user
        user = request.user
        if not check_member_in_project(volume.project, user):
            raise PermissionDenied(detail="User {} is not in project {}."
                .format(user.username, volume.project.name))

        if volume.app:
            raise ValidationError(detail="The volume is being used by \
application {}, delete the application first.".format(volume.app.name))

        # Delete the volume instance
        destroyer = VolumeDestroyer(volume=volume)
        destroyer.destroy_volume()

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 7
Project: wanggeService   Author: pchaos   File: __init__.py    License: MIT License 6 votes vote down vote up
def stockcode_detail(request, pk, format=None):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        values = SC.objects.get(pk=pk)
    except SC.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ListingSerializer(values)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ListingSerializer(values, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        values.delete()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 8
Project: wanggeService   Author: pchaos   File: __init__.py    License: MIT License 6 votes vote down vote up
def ZXG_detail(request, pk, format=None):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        values = BlockDetail.objects.get(pk=pk)
    except BlockDetail.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = BKDetailSerializer(values)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = BKDetailSerializer(values, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        values.delete()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 9
Project: wanggeService   Author: pchaos   File: __init__.py    License: MIT License 6 votes vote down vote up
def stockcode_detail(request, pk, format=None):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        values = SC.objects.get(pk=pk)
    except SC.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ListingSerializer(values)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ListingSerializer(values, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        values.delete()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 10
Project: wanggeService   Author: pchaos   File: __init__.py    License: MIT License 6 votes vote down vote up
def BK_detail(request, pk, format=None):
    """
    Retrieve, update or delete a snippet instance.
    """
    try:
        values = BlockDetail.objects.get(pk=pk)
    except BlockDetail.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = BKDetailSerializer(values)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = BKDetailSerializer(values, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        values.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

# from .hsgtcgholdview import HSGTCG 
Example 11
def test_delete_refresth_token(self):
        self.client.credentials(
            HTTP_AUTHORIZATION='JWT ' + utils.jwt_encode_handler(
                utils.jwt_payload_handler(self.user)))
        response = self.client.delete(self.detail_url)
        self.assertEqual(
            response.status_code,
            status.HTTP_204_NO_CONTENT,
            (response.status_code, response.content)
        )
        response = self.client.delete(self.detail_url1)
        self.assertEqual(
            response.status_code,
            status.HTTP_404_NOT_FOUND,
            (response.status_code, response.content)
        ) 
Example 12
Project: kobo-predict   Author: awemulya   File: xform_viewset.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def share(self, request, *args, **kwargs):
        self.object = self.get_object()

        data = {}
        for key, val in request.data.iteritems():
            data[key] = val
        data.update({'xform': self.object.pk})

        serializer = ShareXFormSerializer(data=data)

        if serializer.is_valid():
            serializer.save()
        else:
            return Response(data=serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 13
Project: kobo-predict   Author: awemulya   File: project_viewset.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def star(self, request, *args, **kwargs):
        user = request.user
        project = get_object_or_404(Project, pk=kwargs.get('pk'))

        if request.method == 'DELETE':
            project.user_stars.remove(user)
        elif request.method == 'POST':
            project.user_stars.add(user)
        elif request.method == 'GET':
            users = project.user_stars.values('pk')
            user_profiles = UserProfile.objects.filter(user__in=users)
            serializer = UserProfileSerializer(user_profiles,
                                               context={'request': request},
                                               many=True)

            return Response(serializer.data)

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 14
Project: timed-backend   Author: adfinis-sygroup   File: test_report.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_report_update_bulk(auth_client):
    task = TaskFactory.create()
    report = ReportFactory.create(user=auth_client.user)

    url = reverse("report-bulk")

    data = {
        "data": {
            "type": "report-bulks",
            "id": None,
            "relationships": {"task": {"data": {"type": "tasks", "id": task.id}}},
        }
    }

    response = auth_client.post(url + "?editable=1", data)
    assert response.status_code == status.HTTP_204_NO_CONTENT

    report.refresh_from_db()
    assert report.task == task 
Example 15
Project: timed-backend   Author: adfinis-sygroup   File: test_report.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_report_update_bulk_verify_reviewer(auth_client):
    user = auth_client.user
    report = ReportFactory.create(user=user)
    report.task.project.reviewers.add(user)

    url = reverse("report-bulk")

    data = {
        "data": {
            "type": "report-bulks",
            "id": None,
            "attributes": {"verified": True, "comment": "some comment"},
        }
    }

    response = auth_client.post(url + "?editable=1&reviewer={0}".format(user.id), data)
    assert response.status_code == status.HTTP_204_NO_CONTENT

    report.refresh_from_db()
    assert report.verified_by == user
    assert report.comment == "some comment" 
Example 16
Project: REST-API   Author: codingforentrepreneurs   File: tests.py    License: MIT License 6 votes vote down vote up
def test_status_delete(self):
        data = self.create_item()
        data_id = data.get("id")
        rud_url = api_reverse('api-status:detail', kwargs={"id": data_id})
        rud_data = {
            'content': "another new content"
        }
        '''
        delete method / delete
        '''
        del_response = self.client.delete(rud_url, format='json')
        self.assertEqual(del_response.status_code, status.HTTP_204_NO_CONTENT)
        '''
        Not found
        '''
        get_response = self.client.get(rud_url, format='json')
        self.assertEqual(get_response.status_code, status.HTTP_404_NOT_FOUND) 
Example 17
Project: django-puppy-store   Author: realpython   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_valid_update_puppy(self):
        response = client.put(
            reverse('get_delete_update_puppy', kwargs={'pk': self.muffin.pk}),
            data=json.dumps(self.valid_payload),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) 
Example 18
Project: django-puppy-store   Author: realpython   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_valid_delete_puppy(self):
        response = client.delete(
            reverse('get_delete_update_puppy', kwargs={'pk': self.muffin.pk}))
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) 
Example 19
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def scale(self, request, **kwargs):
        self.get_object().scale(request.user, request.data)
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 20
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def logs(self, request, **kwargs):
        app = self.get_object()
        try:
            logs = app.logs(request.query_params.get('log_lines', str(settings.LOG_LINES)))
            return HttpResponse(logs, status=status.HTTP_200_OK, content_type='text/plain')
        except NotFound:
            return HttpResponse(status=status.HTTP_204_NO_CONTENT)
        except ServiceUnavailable:
            # TODO make 503
            return HttpResponse("Error accessing logs for {}".format(app.id),
                                status=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                content_type='text/plain') 
Example 21
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def delete(self, request, **kwargs):
        appSettings = self.get_app().appsettings_set.latest()
        addresses = self.get_serializer().validate_whitelist(request.data.get('addresses'))

        unfound_addresses = set(addresses) - set(appSettings.whitelist)
        if len(unfound_addresses) != 0:
            raise UnprocessableEntity('addresses {} does not exist in whitelist'.format(unfound_addresses))  # noqa
        addresses = list(set(appSettings.whitelist) - set(addresses))
        appSettings.new(self.request.user, whitelist=addresses)
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 22
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def detach(self, request, *args, **kwargs):
        try:
            self.get_object().detach(*args, **kwargs)
        except Http404:
            raise

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 23
Project: controller   Author: deis   File: views.py    License: MIT License 5 votes vote down vote up
def destroy(self, request, **kwargs):
        user = get_object_or_404(User, username=kwargs['username'])
        user.is_superuser = user.is_staff = False
        user.save(update_fields=['is_superuser', 'is_staff'])
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 24
Project: py2swagger   Author: Arello-Mobile   File: method.py    License: MIT License 5 votes vote down vote up
def responses(self):
        """
        Collects method responses

        :return: swagger responses object
        :rtype: OrderedDict
        """
        responses = OrderedDict()
        responses.update(self.introspector.responses)
        responses.update(super(BaseMethodIntrospector, self).responses)

        serializer = self._get_serializer()

        if serializer and not responses.get(200, None):
            si = SerializerIntrospector(serializer)
            if 'list' in self.method.lower():
                pagination_introspector = get_pagination_introspector(self.view, si=si)
                responses.update(pagination_introspector.responses)
            else:
                response = OrderedDict([
                    ('description', 'Default response'),
                    ('schema', si.build_response_object()['schema']),
                ])
                responses[200] = response

        status_code = self.STATUS_CODES.get(self.method, self.DEFAULT_STATUS_CODE)
        response = responses.pop(200, None)
        # TODO this code wants to be rewritten
        if response:
            if status_code == status.HTTP_204_NO_CONTENT:
                response.pop('schema', None)
            if not responses.get(status_code, None):
                responses[status_code] = response

        if status_code not in responses:
            response = OrderedDict([
                ('description', 'Empty response'),
            ])
            responses[status_code] = response

        return responses 
Example 25
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def close(self, request, pk=None):
        approval_request = self.get_object()
        approval_request.close()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 26
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def cspreport(request):
    try:
        data = json.loads(request.body.decode())
        detail = data["csp-report"]["violated-directive"]
        logger.error(f"csp error: {detail}", extra=data)
        return Response(None, status=status.HTTP_204_NO_CONTENT)
    except (ValueError, KeyError):
        logger.warn(f"unparsable csp error", extra={"body": request.body.decode()})
        return Response({"error": "unparsable csp report"}, status=status.HTTP_400_BAD_REQUEST) 
Example 27
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def list(self, *args, **kwargs):
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 28
Project: hummer   Author: wangtaoking1   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def destroy(self, request, *args, **kwargs):
        """
        Destroy an application instance.
        """
        application = self.get_object()

        logger.info("user {} deletes application: {}.".format(
            request.user.username, application.name))

        destroyer = ApplicationDestroyer(application=application)
        destroyer.destroy_application_instance()

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example 29
Project: resolwe   Author: genialis   File: test_collection.py    License: Apache License 2.0 5 votes vote down vote up
def test_patch(self):
        data = {"name": "New collection"}
        resp = self._patch(1, data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        p = Collection.objects.get(pk=1)
        self.assertEqual(p.name, "New collection")

        # protected field
        data = {"created": "3042-01-01T09:00:00"}
        resp = self._patch(1, data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)
        p = Collection.objects.get(pk=1)
        self.assertEqual(p.created.isoformat(), self.collection1.created.isoformat()) 
Example 30
Project: resolwe   Author: genialis   File: test_collection.py    License: Apache License 2.0 5 votes vote down vote up
def test_delete(self):
        resp = self._delete(1, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)
        collection_exists = Collection.objects.filter(pk=1).exists()
        self.assertFalse(collection_exists)