Python rest_framework.status.HTTP_400_BAD_REQUEST Examples

The following are 30 code examples for showing how to use rest_framework.status.HTTP_400_BAD_REQUEST(). 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: django-puppy-store   Author: realpython   File: views.py    License: MIT License 6 votes vote down vote up
def get_post_puppies(request):
    # get all puppies
    if request.method == 'GET':
        puppies = Puppy.objects.all()
        serializer = PuppySerializer(puppies, many=True)
        return Response(serializer.data)
    # insert a new record for a puppy
    if request.method == 'POST':
        data = {
            'name': request.data.get('name'),
            'age': int(request.data.get('age')),
            'breed': request.data.get('breed'),
            'color': request.data.get('color')
        }
        serializer = PuppySerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
Example 3
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.

    Adds support the DRF default to also handle django.core.exceptions.ValidationError

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    response = original_exception_handler(exc, context)

    if response:
        return response

    elif isinstance(exc, DjangoValidationError):
        data = {"messages": exc.messages}
        set_rollback()
        return Response(data, status=status.HTTP_400_BAD_REQUEST)

    return None 
Example 4
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 5
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 6
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def approve(self, request, pk=None):
        approval_request = self.get_object()

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

        try:
            approval_request.approve(approver=request.user, comment=request.data.get("comment"))
        except ApprovalRequest.NotActionable:
            return Response(
                {"error": "This approval request has already been approved or rejected."},
                status=status.HTTP_400_BAD_REQUEST,
            )
        except ApprovalRequest.CannotActOnOwnRequest:
            return Response(
                {"error": "You cannot approve your own approval request."},
                status=status.HTTP_403_FORBIDDEN,
            )

        return Response(ApprovalRequestSerializer(approval_request).data) 
Example 7
Project: django-rest-registration   Author: apragacz   File: test_reset_password.py    License: MIT License 6 votes vote down vote up
def test_reset_expired(self):
        timestamp = int(time.time())
        old_password = 'password1'
        new_password = 'eaWrivtig5'
        user = self.create_test_user(password=old_password)
        with patch('time.time',
                   side_effect=lambda: timestamp):
            signer = ResetPasswordSigner({'user_id': user.pk})
            data = signer.get_signed_data()
        data['password'] = new_password
        request = self.create_post_request(data)
        with patch('time.time',
                   side_effect=lambda: timestamp + 3600 * 24 * 8):
            response = self.view_func(request)
        self.assert_invalid_response(response, status.HTTP_400_BAD_REQUEST)
        user.refresh_from_db()
        self.assertTrue(user.check_password(old_password)) 
Example 8
Project: django-rest-registration   Author: apragacz   File: test_verify_email.py    License: MIT License 6 votes vote down vote up
def test_expired(self):
        self.setup_user()
        timestamp = time.time()
        with patch('time.time',
                   side_effect=lambda: timestamp):
            signer = RegisterEmailSigner({
                'user_id': self.user.pk,
                'email': self.new_email,
            })
            data = signer.get_signed_data()
        request = self.create_post_request(data)
        with patch('time.time',
                   side_effect=lambda: timestamp + 3600 * 24 * 8):
            response = self.view_func(request)
        self.assert_invalid_response(response, status.HTTP_400_BAD_REQUEST)
        self.user.refresh_from_db()
        self.assertEqual(self.user.email, self.email) 
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 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 11
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 12
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 13
Project: resolwe   Author: genialis   File: test_data.py    License: Apache License 2.0 6 votes vote down vote up
def test_post_invalid_fields(self):
        data_n = Data.objects.count()

        self.data["collection"] = {"id": 42}
        resp = self._post(self.data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(
            resp.data["collection"][0],
            "Invalid collection value: {'id': 42} - object does not exist.",
        )

        self.data["collection"] = {"id": 1}
        self.data["process"] = {"id": 42}
        resp = self._post(self.data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(
            str(resp.data["process"][0]),
            "Invalid process value: {'id': 42} - object does not exist.",
        )

        self.assertEqual(Data.objects.count(), data_n) 
Example 14
Project: resolwe   Author: genialis   File: test_permissions.py    License: Apache License 2.0 6 votes vote down vote up
def test_share_by_email(self):
        assign_perm("view_collection", self.user1, self.collection)
        assign_perm("share_collection", self.user1, self.collection)

        data = {"users": {"add": {self.user2.email: ["view"]}}}
        resp = self._detail_permissions(self.collection.pk, data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertEqual(
            UserObjectPermission.objects.filter(user=self.user2).count(), 1
        )

        # Check if error is raise when trying to share with duplicated email.
        data = {"users": {"add": {self.user3.email: ["view"]}}}
        resp = self._detail_permissions(self.collection.pk, data, self.user1)
        self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(
            resp.data["detail"], "Cannot uniquely determine user: user1@test.com"
        ) 
Example 15
Project: resolwe   Author: genialis   File: mixins.py    License: Apache License 2.0 6 votes vote down vote up
def slug_exists(self, request):
        """Check if given url slug exists.

        Check if slug given in query parameter ``name`` exists. Return
        ``True`` if slug already exists and ``False`` otherwise.

        """
        if not request.user.is_authenticated:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        if "name" not in request.query_params:
            return Response(
                {"error": "Query parameter `name` must be given."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        queryset = self.get_queryset()
        slug_name = request.query_params["name"]
        return Response(queryset.filter(slug__iexact=slug_name).exists()) 
Example 16
Project: longclaw   Author: JamesRamm   File: api.py    License: MIT License 6 votes vote down vote up
def create(self, request):
        """Create a new product request
        """

        variant_id = request.data.get("variant_id", None)
        if variant_id is not None:
            variant = ProductVariant.objects.get(id=variant_id)
            product_request = ProductRequest(variant=variant)
            product_request.save()
            serializer = self.serializer_class(product_request)
            response = Response(data=serializer.data, status=status.HTTP_201_CREATED)
        else:
            response = Response(
                {"message": "Missing 'variant_id'"},
                status=status.HTTP_400_BAD_REQUEST)

        return response 
Example 17
Project: certificate-generator-server-archive   Author: JBossOutreach   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response_data['is_student'] = will_it_raise_exception(lambda: user.student)
            response_data['is_organization'] = will_it_raise_exception(lambda: user.organization)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
Example 18
Project: onehome-server   Author: michwh   File: views.py    License: MIT License 6 votes vote down vote up
def post(self, request, format=None):
        data = request.data
        if User.objects.filter(username__exact=data.get('username')):
            return Response({"stateCode": 201, "msg": "用户已存在"}, 201)
        if User.objects.filter(email__exact=data.get('email')):
            return Response({"stateCode": 202, "msg": "邮箱已被注册"}, 201)
        new_user = {
            'actual_name': data.get('actual_name'),
            'student_id': data.get('student_id'),
            'username': data.get('username'),
            'email': data.get('email'),
            'password': make_password(data.get('password')),
            'student_card_image_url': data.get('student_card_image_url')
        }
        # print(new_user)
        serializer = RegisterSerializer(data=new_user)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response({"stateCode": 200, "msg": "注册成功"}, 200)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)


# 登录 
Example 19
Project: desec-stack   Author: desec-io   File: pagination.py    License: MIT License 6 votes vote down vote up
def get_paginated_response(self, data):
        pagination_required = self.has_next or self.has_previous
        if not pagination_required:
            return Response(data)

        url = self.request.build_absolute_uri()
        pagination_map = {'first': replace_query_param(url, self.cursor_query_param, '')}

        if self.cursor_query_param not in self.request.query_params:
            count = self.queryset.count()
            data = {
                'detail': f'Pagination required. You can query up to {self.page_size} items at a time ({count} total). '
                          'Please use the `first` page link (see Link header).',
            }
            headers = self.construct_headers(pagination_map)
            return Response(data, headers=headers, status=status.HTTP_400_BAD_REQUEST)

        pagination_map.update(prev=self.get_previous_link(), next=self.get_next_link())
        headers = self.construct_headers(pagination_map)
        return Response(data, headers=headers) 
Example 20
Project: desec-stack   Author: desec-io   File: test_rrsets.py    License: MIT License 6 votes vote down vote up
def test_create_my_rr_sets_type_restriction(self):
        for subname in ['', 'create-my-rr-sets', 'foo.create-my-rr-sets', 'bar.baz.foo.create-my-rr-sets']:
            for data in [
                {'subname': subname, 'ttl': 60, 'type': 'a'},
                {'subname': subname, 'records': ['10 example.com.'], 'ttl': 60, 'type': 'txt'}
            ] + [
                {'subname': subname, 'records': ['10 example.com.'], 'ttl': 60, 'type': type_}
                for type_ in self.DEAD_TYPES
            ] + [
                {'subname': subname, 'records': ['set.an.example. get.desec.io. 2584 10800 3600 604800 60'],
                 'ttl': 60, 'type': type_}
                for type_ in self.RESTRICTED_TYPES
            ]:
                response = self.client.post_rr_set(self.my_domain.name, **data)
                self.assertStatus(response, status.HTTP_400_BAD_REQUEST)

                response = self.client.get_rr_sets(self.my_domain.name)
                self.assertStatus(response, status.HTTP_200_OK)
                self.assertRRSetsCount(response.data, [data], count=0) 
Example 21
Project: desec-stack   Author: desec-io   File: test_rrsets.py    License: MIT License 6 votes vote down vote up
def test_update_my_rr_sets(self):
        for subname in self.SUBNAMES:
            with self.assertPdnsRequests(self.requests_desec_rr_sets_update(name=self.my_rr_set_domain.name)):
                data = {'records': ['2.2.3.4'], 'ttl': 3630, 'type': 'A', 'subname': subname}
                response = self.client.put_rr_set(self.my_rr_set_domain.name, subname, 'A', data)
                self.assertStatus(response, status.HTTP_200_OK)

            response = self.client.get_rr_set(self.my_rr_set_domain.name, subname, 'A')
            self.assertStatus(response, status.HTTP_200_OK)
            self.assertEqual(response.data['records'], ['2.2.3.4'])
            self.assertEqual(response.data['ttl'], 3630)

            response = self.client.put_rr_set(self.my_rr_set_domain.name, subname, 'A', {'records': ['2.2.3.5']})
            self.assertStatus(response, status.HTTP_400_BAD_REQUEST)

            response = self.client.put_rr_set(self.my_rr_set_domain.name, subname, 'A', {'ttl': 3637})
            self.assertStatus(response, status.HTTP_400_BAD_REQUEST) 
Example 22
Project: MPContribs   Author: materialsproject   File: views.py    License: MIT License 5 votes vote down vote up
def rest_submission(request):
    if request.method == "POST":
        serializer = QMCDBSetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response([serializer.errors], status=status.HTTP_400_BAD_REQUEST)
    return HttpResponse(status=400) 
Example 23
Project: django-puppy-store   Author: realpython   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_create_invalid_puppy(self):
        response = client.post(
            reverse('get_post_puppies'),
            data=json.dumps(self.invalid_payload),
            content_type='application/json'
        )
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 
Example 24
Project: django-puppy-store   Author: realpython   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_invalid_update_puppy(self):
        response = client.put(
            reverse('get_delete_update_puppy', kwargs={'pk': self.muffin.pk}),
            data=json.dumps(self.invalid_payload),
            content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) 
Example 25
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def request_approval(self, request, pk=None):
        revision = self.get_object()

        if revision.approval_status is not None:
            return Response(
                {"error": "This revision already has an approval request."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        approval_request = revision.request_approval(creator=request.user)

        return Response(
            ApprovalRequestSerializer(approval_request).data, status=status.HTTP_201_CREATED
        ) 
Example 26
Project: normandy   Author: mozilla   File: views.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def get(self, request, *, generation, seed):
        if generation != "v1":
            return Response(
                {"error": "Invalid identicon generation, only v1 is supported."},
                status=status.HTTP_400_BAD_REQUEST,
            )

        genome = shield_identicon.Genome(seed)
        identicon_svg = shield_identicon.generate_svg(genome)
        return HttpResponse(identicon_svg, content_type="image/svg+xml") 
Example 27
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 28
Project: django-rest-registration   Author: apragacz   File: api_views.py    License: MIT License 5 votes vote down vote up
def assert_response_is_bad_request(response):
    assert_invalid_response(
        response,
        expected_status_code=status.HTTP_400_BAD_REQUEST,
    ) 
Example 29
Project: django-rest-registration   Author: apragacz   File: test_login.py    License: MIT License 5 votes vote down vote up
def test_invalid(self):
        request = self.create_post_request({
            'login': self.user.username,
            'password': 'blah',
        })
        self.add_session_to_request(request)
        response = self.view_func(request)
        self.assert_invalid_response(response, status.HTTP_400_BAD_REQUEST) 
Example 30
Project: django-rest-registration   Author: apragacz   File: test_logout.py    License: MIT License 5 votes vote down vote up
def _test_revoke_nonexistent_token_failure(self, add_session=True):
        self.assertFalse(Token.objects.filter(user=self.user).exists())
        request = self.create_post_request({
            'revoke_token': True,
        })
        if add_session:
            self.add_session_to_request(request)
        force_authenticate(request, user=self.user)
        response = self.view_func(request)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)