I Have just started with django-rest-framework. Pretty enthousiastic about it, except for the fact there are very little examples available. getting the api working is going
Probably not relevant anymore based on recent years downvotes.. It was relevant in '12 tho :)
Django-rest-framework actually have very many examples..
Take a look at http://django-rest-framework.org, http://django-rest-framework.org/contents.html and http://rest.ep.io/ for some good examples and documentation.
If you are designing a REST function by yourself, not using any of the django-rest-framework magic (like rest.ep.io) to generate it for you, you should look into mixin (http://django-rest-framework.org/howto/mixin.html).
If you want to restrict to only get methods. Just use def get(...) and the mixin class.
Example from link provided:
curl -X GET http://rest.ep.io/mixin/
urls.py
from djangorestframework.compat import View
from djangorestframework.mixins import ResponseMixin
from djangorestframework.renderers import DEFAULT_RENDERERS
from djangorestframework.response import Response
from django.conf.urls.defaults import patterns, url
from django.core.urlresolvers import reverse
class ExampleView(ResponseMixin, View):
renderers = DEFAULT_RENDERERS
def get(self, request):
response = Response(200, {'description': 'Some example content',
'url': reverse('mixin-view')})
return self.render(response)
urlpatterns = patterns('',
url(r'^$', ExampleView.as_view(), name='mixin-view'),
)
Sorry for necro, but I stumbled upon this question looking for a similar issue.
I only wanted to allow retrieve()
but not to list()
. What I ended up doing:
from rest_framework import viewsets
from rest_framework.exceptions import MethodNotAllowed
from myapp.models import MyModel
class MyViewSet(viewsets.ModelViewSet):
http_method_names = ["get"]
queryset = MyModel.objects.all()
serializer_class = MySerializer
def list(self, request, *args, **kwargs):
raise MethodNotAllowed("GET")
As almost everything in django-rest-framework, once you find it out, its very simple. In the urls in stead of using ListOrCreateModelView I had to use ListModelView.
If you are using ModelViewSet and still want to restrict some methods you can add http_method_names
.
Example:
class SomeModelViewSet(viewsets.ModelViewSet):
queryset = SomeModel.objects.all()
serializer_class = SomeModelSerializer
http_method_names = ['get', 'post', 'head']
Once you do this, get
, post
and head
will be allowed. But put
, patch
and delete
will not be allowed.