Note that there are some explanatory texts on larger screens.

plurals
  1. POBackbone Create model with Django Rest Framework
    primarykey
    data
    text
    <p>Im trying to create a new model with a rest api using Django Rest Framework.</p> <p>This is my serializer:</p> <pre><code>class FooSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Foo </code></pre> <p>This is my view.py</p> <pre><code>@api_view(['POST', 'GET','DELETE','OPTIONS']) def foos(request): """ API endpoint to create, delete and get foos """ authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) model = Foo serializer_class = FooSerializer if request.method == "POST": data = JSONParser().parse(request) serializer = FooSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) else: return JSONResponse(serializer.errors, status=400) return Response(serializer.data) </code></pre> <p>Then in my backbone view:</p> <pre><code> foo = new Foo name:'Bla di bla di' foo.save() </code></pre> <p>Noting happens except for the OPTIONS to fail, there is no POST.</p> <p><img src="https://i.stack.imgur.com/LvLfH.png" alt="failing OPTIONS"></p> <pre><code>OPTIONS http://127.0.0.1:8080/api/foo/ </code></pre> <p>I dont know what to do, this does not happen if I leave out the contentType:"application/json" part of the post (when doing a manual post)</p> <p>It works with CURL in my terminal.</p> <p>In my chrome Inspector > Network I get this:</p> <pre><code>Request URL:http://127.0.0.1:8080/api/foo/ Request Headersview source Access-Control-Request-Headers:accept, origin, authorization, content-type Access-Control-Request-Method:POST Cache-Control:no-cache Origin:http://localhost:8000 Pragma:no-cache </code></pre> <p>Request, and Response is empty.</p> <p><strong>EDIT</strong></p> <p>I turned of the server with the Rest APi and the exact same thing happens! So this tels me one thing, its not anything to do with the server. Must be the AJAX stuff. </p> <p><em>Im completely confused</em> :-(</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload