From cd546fdaee5f9f58c1c73b6ee93d0f1b19e02790 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Se=CC=81bastien=20Be=CC=81al?= Date: Sat, 17 Mar 2012 20:27:01 +0900 Subject: [PATCH 1/2] raise 401 instead of 403 when user is not authenticated --- djangorestframework/permissions.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/djangorestframework/permissions.py b/djangorestframework/permissions.py index 03d78c2ea..d11740831 100644 --- a/djangorestframework/permissions.py +++ b/djangorestframework/permissions.py @@ -23,6 +23,11 @@ __all__ = ( SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] +_401_UNAUTHORIZED = ErrorResponse( + status.HTTP_401_UNAUTHORIZED, + {'detail': 'The request requires user authentication.'}, + {'WWW-Authenticate': 'Basic realm="API"'}) + _403_FORBIDDEN_RESPONSE = ErrorResponse( status.HTTP_403_FORBIDDEN, {'detail': 'You do not have permission to access this resource. ' + @@ -66,7 +71,7 @@ class IsAuthenticated(BasePermission): def check_permission(self, user): if not user.is_authenticated(): - raise _403_FORBIDDEN_RESPONSE + raise _401_UNAUTHORIZED class IsAdminUser(BasePermission): From 8a6ae28ada40a9da387043eb9d4f5b1eacc3592a Mon Sep 17 00:00:00 2001 From: Sebastien Beal Date: Fri, 28 Dec 2012 09:55:19 +0900 Subject: [PATCH 2/2] example of .validate() method between multiple fields --- docs/api-guide/serializers.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 19efde3c7..baa296d3c 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -112,6 +112,21 @@ Your `validate_` methods should either just return the `attrs` dictio To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. + from rest_framework import serializers + + class QueryParameterSerializer(serializers.Serializer): + start = serializers.DateTimeField(required=False, default='') + stop = serializers.DateTimeField(required=False, default='') + + def validate(self, attrs): + """ + Check that the start is before the stop. + """ + if attrs['start'] and attrs['stop']: + if attrs['start'] < attrs['stop']: + raise serializers.ValidationError("Range finish must come after start") + return attrs + ## Saving object state Serializers also include a `.save()` method that you can override if you want to provide a method of persisting the state of a deserialized object. The default behavior of the method is to simply call `.save()` on the deserialized object instance.