0

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))

    
]

4
  • show the contents of the urls.py file which will present somewhere adjacent to your views.py file. Commented Jun 27, 2020 at 11:47
  • Okei, have added it now! Commented Jun 28, 2020 at 11:47
  • your TaskView view is not present in the urls.py file. Commented Jun 28, 2020 at 11:51
  • ah damn sorry that was the wrong urls.py, ive edited it now. Commented Jun 28, 2020 at 17:06

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Yes but how do i call it from my app?
In order to get single object you should make an http request like: "GET /task/1/" where "1" is ID of a particular object you would like to retrieve. I you want to create objects you use "POST /task/" with a payload of data necessary to create a new object instance. Such structure can be defined by your model serializer (django-rest-framework.org/api-guide/serializers/…).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.