Python rest_framework.status.HTTP_400_BAD_REQUEST Examples

The following are 30 code examples of rest_framework.status.HTTP_400_BAD_REQUEST(). 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 django-puppy-store with MIT License 7 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
Source File: test_reset_password.py    From django-rest-registration with 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 #4
Source File: test_rrsets.py    From desec-stack with 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 #5
Source File: views.py    From normandy with 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 #6
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 #7
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 #8
Source File: views.py    From normandy with 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 #9
Source File: test_verify_email.py    From django-rest-registration with 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 #10
Source File: test_rrsets.py    From desec-stack with 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 #11
Source File: pagination.py    From desec-stack with 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 #12
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 #13
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 #14
Source File: api.py    From longclaw with 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 #15
Source File: views.py    From certificate-generator-server-archive with 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 #16
Source File: mixins.py    From resolwe with 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 #17
Source File: test_permissions.py    From resolwe with 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 #18
Source File: views.py    From onehome-server with 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
Source File: test_data.py    From resolwe with 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 #20
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 #21
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 #22
Source File: views.py    From django-rest-framework-docs with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def post(self, request, *args, **kwargs):
        serializer = ResetPasswordSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
        return Response({"msg": "Password updated successfully."}, status=status.HTTP_200_OK) 
Example #23
Source File: api.py    From longclaw with MIT License 5 votes vote down vote up
def create_order_with_token(request):
    """
    Create an order using an existing transaction ID.
    This is useful for capturing the payment outside of
    longclaw - e.g. using paypals' express checkout or
    similar
    """
    # Get the request data
    try:
        address = request.data['address']
        shipping_option = request.data.get('shipping_option', None)
        email = request.data['email']
        transaction_id = request.data['transaction_id']
    except KeyError:
        return Response(data={"message": "Missing parameters from request data"},
                        status=status.HTTP_400_BAD_REQUEST)

    # Create the order
    order = create_order(
        email,
        request,
        addresses=address,
        shipping_option=shipping_option,
    )

    order.payment_date = timezone.now()
    order.transaction_id = transaction_id
    order.save()
    # Once the order has been successfully taken, we can empty the basket
    destroy_basket(request)

    return Response(data={"order_id": order.id}, status=status.HTTP_201_CREATED) 
Example #24
Source File: views.py    From onehome-server with MIT License 5 votes vote down vote up
def post(self, request):
        data = request.data
        # username = data.get('username')
        serializer = ProductSerializer(data=data)

        if request.user.is_authenticated:
            # print(data)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                return Response({"stateCode": 200, "msg": "发布成功"}, 200)
            return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
        else:
            return Response({"stateCode": 201, "msg": "没有上传权限"}, 201) 
Example #25
Source File: test_user_management.py    From desec-stack with MIT License 5 votes vote down vote up
def assertChangeEmailFailureAddressTakenResponse(self, response):
        return self.assertContains(
            response=response,
            text="You already have another account with this email address.",
            status_code=status.HTTP_400_BAD_REQUEST
        ) 
Example #26
Source File: tests.py    From longclaw with MIT License 5 votes vote down vote up
def test_shipping_option_endpoint_without_destination(self):
        params = {
            'country_code': self.country.pk,
        }
        response = self.get_test('longclaw_applicable_shipping_rate_list', params=params, success_expected=False)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertEqual(response.data['message'], "Destination address is required for rates to 11.") 
Example #27
Source File: test_rrsets.py    From desec-stack with MIT License 5 votes vote down vote up
def test_create_my_rr_sets_unknown_type(self):
        for _type in ['AA', 'ASDF']:
            with self.assertPdnsRequests(
                    self.request_pdns_zone_update_unknown_type(name=self.my_domain.name, unknown_types=_type)
            ):
                response = self.client.post_rr_set(self.my_domain.name, records=['1234'], ttl=3660, type=_type)
                self.assertStatus(response, status.HTTP_400_BAD_REQUEST) 
Example #28
Source File: views.py    From Django-Bookworm with MIT License 5 votes vote down vote up
def post(self, request):
        serializer = ChapterSerializer(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) 
Example #29
Source File: views.py    From Django-Bookworm with MIT License 5 votes vote down vote up
def put(self, request, pk):
        chapter = get_object_or_404(Chapter, pk=pk)
        serializer = ChapterSerializer(chapter, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
Example #30
Source File: api.py    From longclaw with MIT License 5 votes vote down vote up
def shipping_options(request, country=None):
    """
    Get the shipping options for a given country
    """
    try:
        kwargs = get_shipping_cost_kwargs(request, country=country)
    except (utils.InvalidShippingCountry, utils.InvalidShippingDestination) as e:
        return Response(data={'message': e.message}, status=status.HTTP_400_BAD_REQUEST)
    
    country_code = kwargs['country_code']
    settings = kwargs['settings']
    bid = kwargs['basket_id']
    destination = kwargs['destination']
    
    processors = ShippingRateProcessor.objects.filter(countries__in=[country_code])
    if processors:
        if not destination:
            return Response(
                data={
                    "message": "Destination address is required for rates to {}.".format(country_code)
                },
                status=status.HTTP_400_BAD_REQUEST
            )
        for processor in processors:
            processor.get_rates(settings=settings, basket_id=bid, destination=destination)
    
    q = Q(countries__in=[country_code]) | Q(basket_id=bid, destination=None)
    
    if destination:
        q.add(Q(destination=destination, basket_id=''), Q.OR)
        q.add(Q(destination=destination, basket_id=bid), Q.OR)
    
    qrs = models.ShippingRate.objects.filter(q)
    serializer = serializers.ShippingRateSerializer(qrs, many=True)
    return Response(
        data=serializer.data,
        status=status.HTTP_200_OK
    )