Python rest_framework.status.HTTP_204_NO_CONTENT Examples

The following are 30 code examples of rest_framework.status.HTTP_204_NO_CONTENT(). 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 also want to check out all available functions/classes of the module rest_framework.status , or try the search function .
Example #1
Source File: views.py    From django-puppy-store with 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
Source File: views.py    From normandy with 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 #3
Source File: test_report.py    From timed-backend with 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 #4
Source File: __init__.py    From wanggeService with 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 #5
Source File: __init__.py    From wanggeService with 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 #6
Source File: __init__.py    From wanggeService with 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 #7
Source File: __init__.py    From wanggeService with 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
Source File: views.py    From hummer with 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 #9
Source File: views.py    From hummer with 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 #10
Source File: test_report.py    From timed-backend with 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 #11
Source File: test_long_refresh_token_views.py    From django-rest-framework-jwt-refresh-token with MIT License 6 votes vote down vote up
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
Source File: tests.py    From REST-API with 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 #13
Source File: views.py    From normandy with 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 #14
Source File: project_viewset.py    From kobo-predict with 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 #15
Source File: xform_viewset.py    From kobo-predict with 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 #16
Source File: views.py    From controller with 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 #17
Source File: test_event_auth_api.py    From linkedevents with MIT License 5 votes vote down vote up
def test_api_key_delete_sub_organization_event(self):
        self.org_1.admin_users.add(self.user)

        url = reverse('event-detail', kwargs={'pk': self.event_3.id})
        self.client.force_authenticate(self.user)
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_410_GONE) 
Example #18
Source File: test_api.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def test_delete_autonomous_system(self):
        url = reverse(
            "peering-api:autonomoussystem-detail",
            kwargs={"pk": self.autonomous_system.pk},
        )
        response = self.client.delete(url, **self.header)

        self.assertStatus(response, status.HTTP_204_NO_CONTENT)
        self.assertEqual(AutonomousSystem.objects.count(), 0) 
Example #19
Source File: test_api.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def test_delete_autonomous_system(self):
        url = reverse("utils-api:tag-detail", kwargs={"pk": self.tag.pk})
        response = self.client.delete(url, **self.header)

        self.assertStatus(response, status.HTTP_204_NO_CONTENT)
        self.assertEqual(Tag.objects.count(), 0) 
Example #20
Source File: test_api.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def test_delete_bgp_group(self):
        url = reverse("peering-api:bgpgroup-detail", kwargs={"pk": self.bgp_group.pk})
        response = self.client.delete(url, **self.header)

        self.assertStatus(response, status.HTTP_204_NO_CONTENT)
        self.assertEqual(BGPGroup.objects.count(), 0) 
Example #21
Source File: test_api.py    From peering-manager with Apache License 2.0 5 votes vote down vote up
def test_delete_community(self):
        url = reverse("peering-api:community-detail", kwargs={"pk": self.community.pk})
        response = self.client.delete(url, **self.header)

        self.assertStatus(response, status.HTTP_204_NO_CONTENT)
        self.assertEqual(Community.objects.count(), 0) 
Example #22
Source File: test_event_auth_api.py    From linkedevents with MIT License 5 votes vote down vote up
def test_admin_delete_sub_organization_event(self):
        self.org_1.admin_users.add(self.user)

        url = reverse('event-detail', kwargs={'pk': self.event_3.id})
        self.client.force_authenticate(self.user)
        response = self.client.delete(url)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_410_GONE) 
Example #23
Source File: tests_view.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_delete_cost_model_success(self):
        """Test that we can delete an existing rate."""
        cost_model = CostModel.objects.first()
        url = reverse("cost-models-detail", kwargs={"uuid": cost_model.uuid})
        client = APIClient()
        with patch("masu.processor.tasks.update_cost_model_costs.delay"):
            response = client.delete(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)

        # verify the cost model no longer exists
        response = client.get(url, **self.headers)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) 
Example #24
Source File: note_viewset.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def destroy(self, request, *args, **kwargs):
        obj = self.get_object()
        instance = obj.instance
        obj.delete()
        # update mongo data
        instance.parsed_instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT) 
Example #25
Source File: briefcase_api.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        if request.method.upper() == 'HEAD':
            return Response(status=status.HTTP_204_NO_CONTENT,
                            headers=self.get_openrosa_headers(request),
                            template_name=self.template_name)

        xform_def = request.FILES.get('form_def_file', None)
        response_status = status.HTTP_201_CREATED
        username = kwargs.get('username')
        form_user = (username and get_object_or_404(User, username=username)) \
            or request.user

        if not request.user.has_perm(
            'can_add_xform',
            UserProfile.objects.get_or_create(user=form_user)[0]
        ):
            raise exceptions.PermissionDenied(
                detail=_(u"User %(user)s has no permission to add xforms to "
                         "account %(account)s" %
                         {'user': request.user.username,
                          'account': form_user.username}))
        data = {}

        if isinstance(xform_def, File):
            do_form_upload = DoXmlFormUpload(xform_def, form_user)
            dd = publish_form(do_form_upload.publish)

            if isinstance(dd, XForm):
                data['message'] = _(
                    u"%s successfully published." % dd.id_string)
            else:
                data['message'] = dd['text']
                response_status = status.HTTP_400_BAD_REQUEST
        else:
            data['message'] = _(u"Missing xml file.")
            response_status = status.HTTP_400_BAD_REQUEST

        return Response(data, status=response_status,
                        headers=self.get_openrosa_headers(request,
                                                          location=False),
                        template_name=self.template_name) 
Example #26
Source File: project_viewset.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def share(self, request, *args, **kwargs):
        self.object = self.get_object()
        data = dict(request.data.items() + [('project', self.object.pk)])
        serializer = ShareProjectSerializer(data=data)

        if serializer.is_valid():
            if data.get("remove"):
                serializer.remove_user()
            else:
                serializer.save()
                email_msg = data.get('email_msg')

                if email_msg:
                    # send out email message.
                    # serializer.object doesn't exist anymore in DRF, so
                    # we have to pull the user from the DB
                    username = serializer.validated_data['username']
                    user = User.objects.get(username=username)
                    send_mail(SHARE_PROJECT_SUBJECT.format(self.object.name),
                              email_msg,
                              DEFAULT_FROM_EMAIL,
                              (user.email, ))

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

        return Response(status=status.HTTP_204_NO_CONTENT) 
Example #27
Source File: xform_submission_api.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        username = self.kwargs.get('username')
        # if self.request.user.is_anonymous():
        #     if username is None:
        #         # raises a permission denied exception, forces authentication
        #         self.permission_denied(self.request)
        #     else:
        #         user = get_object_or_404(User, username=username.lower())
        #
        #         profile, created = UserProfile.objects.get_or_create(user=user)
        #
        #         if profile.require_auth:
        #             # raises a permission denied exception,
        #             # forces authentication
        #             self.permission_denied(self.request)
        # elif not username:
        #     # get the username from the user if not set
        #     username = (request.user and request.user.username)

        if request.method.upper() == 'HEAD':
            return Response(status=status.HTTP_204_NO_CONTENT,
                            headers=self.get_openrosa_headers(request),
                            template_name=self.template_name)

        is_json_request = is_json(request)

        error, instance = (create_instance_from_json if is_json_request else
                           create_instance_from_xml)(username, request)

        if error or not instance:
            return self.error_response(error, is_json_request, request)
        update_mongo(instance)
        context = self.get_serializer_context()
        serializer = SubmissionSerializer(instance, context=context)
        return Response(serializer.data,
                        headers=self.get_openrosa_headers(request),
                        status=status.HTTP_201_CREATED,
                        template_name=self.template_name) 
Example #28
Source File: connect_viewset.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def reset(self, request, *args, **kwargs):
        context = {'request': request}
        data = request.data if request.data is not None else {}
        if 'token' in request.data:
            serializer = PasswordResetChangeSerializer(data=data,
                                                       context=context)
        else:
            serializer = PasswordResetSerializer(data=data, context=context)

        if serializer.is_valid():
            serializer.save()

            return Response(status=status.HTTP_204_NO_CONTENT)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
Example #29
Source File: source_status.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def _deliver_status(request, status_obj):
    """Deliver status depending on request."""
    if request.method == "GET":
        return Response(status_obj.sources_response, status=status.HTTP_200_OK)
    elif request.method == "POST":
        LOG.info("Delivering source status for Source ID: %s", status_obj.source_id)
        status_thread = threading.Thread(target=status_obj.push_status)
        status_thread.daemon = True
        status_thread.start()
        return Response(status=status.HTTP_204_NO_CONTENT)
    else:
        raise status.HTTP_405_METHOD_NOT_ALLOWED 
Example #30
Source File: test_tokens.py    From desec-stack with MIT License 5 votes vote down vote up
def test_delete_my_token(self):
        token_id = Token.objects.get(user=self.owner, name='testtoken').id
        url = self.reverse('v1:token-detail', pk=token_id)

        response = self.client.delete(url)
        self.assertStatus(response, status.HTTP_204_NO_CONTENT)
        self.assertFalse(Token.objects.filter(pk=token_id).exists())

        response = self.client.get(url)
        self.assertStatus(response, status.HTTP_404_NOT_FOUND)