Skip to content

Instantly share code, notes, and snippets.

View tomchristie's full-sized avatar
🌿

Tom Christie tomchristie

🌿
View GitHub Profile

Filtering

The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.

— [Django documentation][cite]

The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.

The simplest way to filter the queryset of any view that subclasses MultipleObjectAPIView is to override the .get_queryset() method.

@tomchristie
tomchristie / gist:4285537
Created December 14, 2012 13:40
REST framework. CSRF
[13:33:03] <mikeywaites> whats the prefered way to disable csrf for resources?
[13:33:09] <mikeywaites> in v2.x
[13:33:47] <mikeywaites> ping tomchristie
[13:36:06] <tomchristie> mikeywaites: This needs docs.
[13:36:25] <tomchristie> If your using SessionAuthentication answer is dont do that.
[13:36:38] <tomchristie> If you using any other auth, csrf wont apply
[13:36:54] <tomchristie> Django docs have a section on using CSRF with AJAX
[13:37:23] <tomchristie> If you really want to be bad best answer would be use a custom auth
[13:37:37] <tomchristie> Crib from the session auth, and just drop the bit that performs CSRF
# Explicit registry
router = DefaultRouter()
router.register(r'^snippets/', resources.SnippetResource, 'snippet')
router.register(r'^users/', resources.UserResource, 'user')
urlpatterns = router.urlpatterns
# Auto register
router = DefaultRouter()
router.auto_register()
urlpatterns = router.urlpatterns
class LinksSerializer(serializers.Serializer):
next = pagination.NextPageField(source='*')
prev = pagination.PreviousPageField(source='*')
def field_to_native(self, obj, field_name):
if self.source == '*':
return self.to_native(obj)
return super(self, LinksSerializer).field_to_native(obj, field_name)
class IsOwner(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_permission(self, request, view, obj=None):
# Skip the check unless this is an object-level test
if obj is None:
return True
class NoCSRFSessionAuthentication(BaseAuthentication):
"""
Use Django's session framework for authentication.
"""
def authenticate(self, request):
"""
Returns a `User` if the request session currently has a logged in user.
Otherwise returns `None`.
"""
def field_from_native(self, data, files, field_name, into):
into.update(self.from_native(data[field_name]))
from rest_framework import serializers
stuff = {'name': 'toran', 'other_content': {'foo': 'things', 'bar': 'stuff'}}
class ExampleSerializer(serializers.Serializer):
name = serializers.Field()
foo = serializers.Field(source='other_content.foo')
bar = serializers.Field(source='other_content.bar')
serializer = ExampleSerializer(stuff)
# `views.py`
@api_view(['GET', 'POST']) # Or whatever methods the view should support.
def whatever(request):
...
return Response(some_data) # `some_data` should be any native python json-serializable stuff.
# `settings.py`
from rest_framework import exceptions
...
try
data = request.DATA
except exceptions.ParseError
data = '[Invalid data in request]'