Django-Rest-Framework CreateAPIView not working

Viewed 9856

I am trying to implement a simple viewset from django-rest-framework, everything is working OK except for the Create view. The ulr (http://127.0.0.1:8000/api/create/) is loaded with the form to input data but when I hit PUT the data is not loaded in database. Terminal shows the following error: [19/Jun/2019 14:15:29] "GET /api/create/ HTTP/1.1" 404 10318 Not Found: /api/create/

I am following this tutorial to learn to integrate django and react. I've previously tried to implement CRUD views separately but got a circular reference error. I suppose there must be some sort of error with url definitions but I just can't figure out what is wrong.

API urls.py:

from articles.api.views import ArticleViewSet
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'', ArticleViewSet, base_name='articles')
urlpatterns = router.urls

API views.py:

from rest_framework import viewsets
from articles.models import Article
from .serializers import ArticleSerializer

class ArticleViewSet(viewsets.ModelViewSet):
    serializer_class = ArticleSerializer
    queryset = Article.objects.all()

API serializer:

from rest_framework import serializers
from articles.models import Article

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id', 'title', 'content')

Project urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [

    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls')),
    path('api/', include('articles.api.urls')),

]

With this code, when I access the List view the form to add a new record appears below and if I enter data there the record is added to database. But when I go to 'api/create' and submit the form it is not loaded in database. Update and Delete views are working fine.
Thanks for your help!

1 Answers

If you are create an object, just POST to /api/ URL. Not /api/create/. This is because your ArticleViewSet contains CreateAPIView. If you are using like this:

from rest_framework import generics
class ArticleViewSet(generics.CreateAPIView):
    serializer_class = ArticleSerializer
    queryset = Article.objects.all()

Your routers in urls.py does not working if you use CreateAPIView. Your tutorial explains this.

You need to do send POST data /api/ URL for object creation.

  • POST method for create
  • PUT method for edit
  • GET method for list or detail
  • DELETE for delete

operations in viewsets.

If you want to use CreateAPIView(like the above code) you must change urls.py like this.

urlpatterns = [
    url("/api/create/", views.ArticleViewSet.as_view())
]
Related