user13714701
user13714701

Reputation:

Django REST framework viewset API call

I want to make an api call for a viewset.ModelViewset, how can i do this?

This is my views.py

from rest_framework import viewsets

from .serializers import TaskSerializer
from .models import Task
# Create your views here.


class TaskView(viewsets.ModelViewSet):

    queryset = Task.objects.all()
    serializer_class = TaskSerializer

I usually make calls with like this to the back end.

fetch(url, {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
        'X-CSRFToken': csrftoken
      },
      body: JSON.stringify(this.state.activeItem)
    }).then((response) => {

      //Calling to fetchTasks to update the list after edit
      this.fetchTasks()

      //Setting the state back to null
      this.setState({
        activeItem: {
          id: null,
          title: ' ',
          completed: false,
        }
      })

In this example its POST request, but i read inn the Djano REST Framwork docs that the viewset provides actions such as .list() and .create(), ant not .get() or .post(). I was wondering how i can make an api call from my react app to this viewset if this is the case.

This is my urls.py:

from django.urls import path, include
from . import views

from rest_framework import routers
router = routers.DefaultRouter()
router.register('task', views.TaskView, basename = 'Task')


urlpatterns = [

    path('', include(router.urls))

    
]

Upvotes: 0

Views: 1711

Answers (1)

Marek Naskret
Marek Naskret

Reputation: 421

In DRF ViewSets your POST requests are handled by create method on a ViewSet class (default implementation: https://github.com/encode/django-rest-framework/blob/5ce237e00471d885f05e6d979ec777552809b3b1/rest_framework/mixins.py#L12).

A GET request (single object retrieval) is handled by a retrieve method (default implementation: https://github.com/encode/django-rest-framework/blob/5ce237e00471d885f05e6d979ec777552809b3b1/rest_framework/mixins.py#L49).

Upvotes: 1

Related Questions