DRF + React implements TodoList

1. Create a project directory to configure Backend

mkdir django-todo-react
cd django-todo-react
django-admin startproject backend
cd backend
django-admin startapp todo
Copy the code

Register the application Todo

# backend/settings.py

# Application definition
INSTALLED_APPS = [
...
'todo' # here
]
Copy the code

Define the Todo model

# todo/models.py

from django.db import models
# Create your models here.

# add this
class Todo(models.Model) :
    title = models.CharField(max_length=120)
    description = models.TextField()
    completed = models.BooleanField(default=False)

    def _str_(self) :
        return self.title
Copy the code

Data migration

# todo/models.py from django.db import models # Create your models here. # add this python manage.py makemigrations todo  python manage.py migrate todoCopy the code

Register the model with admin

# todo/admin.py

from django.contrib import admin
from .models import Todo # add this

class TodoAdmin(admin.ModelAdmin) : # add this
    list_display = ('title'.'description'.'completed') # add this

# Register your models here.
    admin.site.register(Todo, TodoAdmin) # add this
Copy the code

Create an account check and add a few Todolist

python manage.py createsuperuser
Copy the code

2. Configuration APIs

Registered rest_framework

#backend/settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',]Copy the code

paging

Pagination allows you to control how many objects are returned per page. Enable it to add the following lines to backend/settings.py

#backend/settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination'.'PAGE_SIZE': 10
}
Copy the code

Todo Model serialization

Create a new file todo/serializers

# todo/serializers.py

from rest_framework import serializers
from .models import Todo

class TodoSerializer(serializers.ModelSerializer) :
    class Meta:
      model = Todo
      fields = ('id'.'title'.'description'.'completed')
Copy the code

4. The View

# todo/views.py

from django.shortcuts import render
from rest_framework import viewsets # add this
from .serializers import TodoSerializer # add this
from .models import Todo # add this

class TodoView(viewsets.ModelViewSet) : # add this
    serializer_class = TodoSerializer # add this
    queryset = Todo.objects.all(a)# add this
Copy the code

The view set base class provides the implementation of CRUD operations by default. All we need to do is specify the serializer class and the query set.

5.URLs

Write backend/urls.py files