lundi 4 janvier 2016

POST requests with EmberData and Django REST Framework

I am integrating a django-rest-framework backend and an Ember frontend (with EmberData). These are my versions:

  • Django 1.9
  • djangorestframework 3.3.2
  • django-rest-framework-json-api (latest version from github)
  • ember-cli 1.13.13
  • ember 2.2.0
  • ember-data 2.2.1

GET requests are working fine, but POSTs are not. This is the kind of request coming from EmberData:

{
  "data": {
    "attributes": {
      "name": "The project name",
      "description": "The project description",
      "price": 123
    },
    "relationships": {
      "onwer": {
        "data": null
      }
    },
    "type": "projects"
  }
}

But django is crashing, and reporting:

Page not found ... The current URL, api/projects, didn't match any of these

My URLs are created with a router:

from rest_framework.routers import DefaultRouter

from .viewsets.projects import ProjectViewSet


router = DefaultRouter()
...
router.register(r'projects', ProjectViewSet)
...

and ViewSet:

from rest_framework import viewsets
from rest_framework import filters

from vwrks.models import Project

from ..serializers import ProjectSerializer

class ProjectViewSet(viewsets.ModelViewSet):
    """
    A viewset for viewing and editing Project instances.
    """
    serializer_class = ProjectSerializer
    queryset = Project.objects.all()
    filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter)
    filter_fields = ('seller', 'artist', 'subcategory')
    search_fields = ('name', 'description')

According to the documentation (http://ift.tt/1yWXFKM), ViewSets provide support for .create(), so this POST operation should be supported.

I have also tweaked the trailing slashes for Django, in order to accept POSTs at /projects as EmberData is doing (besides the default /projects/ that Django is expecting)

# EmberData does POST to /projects (not /projects/), so we need this:
APPEND_SLASH = False

The problem that I see is that Django's router does not generate a project-create URL (only project-list and project-detail are listed):

^api/ ^projects/$ [name='project-list']
^api/ ^projects\.(?P<format>[a-z0-9]+)/?$ [name='project-list']
^api/ ^projects/(?P<pk>[^/.]+)/$ [name='project-detail']
^api/ ^projects/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='project-detail']

What can I do to get POSTs requests from EmberData to drf working?




Aucun commentaire:

Enregistrer un commentaire