In this article, you will build a Todo application using React and Django.
React is a javascript framework for developing SPA's(single-page applications). React has detailed documentation and a bigger ecosystem.
Django is a Python web framework to build the backend of the web application. Django simplifies the common web practices of web development. Django is a more robust, scalable framework and has huge community support.
In this project, React is used as a Front-end framework or client-side framework to create user-interface and send API requests to the backend. Django used to build API endpoints to receive data from front-end.
Prerequisites
Basic knowledge in both React and Django is required. You check out these get started with React and Python.
React documentation : You check react official docs to get started, they provided with easy understanding of concepts.
Django Tutorial
Let's start or project, Before start check whether python and Nodejs is installed.
To download python and Nodejs from here
- Python
- Node JS
Step 1 : Setting up Backend
Open a terminal and enter the following command to create a new project directory.
mkdir todo-django-react
cd todo-django-react
Create an virtual environment and activate it
python -m venv env
env\Scripts\activate
Now, install django
pip install django
Create new project name backend and navigate to folder
django-admin startproject backend
cd backend
Start a new application called todo
python manage.py startapp todo
Run migrations
python manage.py migrate
Open the root folder in any code editor (VScode, Atom etc…) and here we registering our application so Django will recognize it.
Navigate to backend/settings.py
and todo in INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'todo',
]
Create our Todo Model:
Open todo/model.py
and type the following code:
class TodoModel(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
completed = models.BooleanField(default=False)
def __str__(self):
return self.title
The above code snippets describe three field of our todo model,
Title
: Name of todo
description
: more details about the individual todo
completed
: it shows the status of todo whether it completed or not
Now run migration to add model to the database
python manage.py makemigrations todo
python manage.py migrate todo
Django provides us a default admin interface to test CRUD on our model. Lets add our model to admin page
Open todo/admin.py
and enter following code
from .models import TodoModel
admin.site.register(TodoModel)
Then, save changes.
You will need to create a superuser to access the admin page. Run the following cmd in terminal to create
python manage.py createsuperuser
Terminal will prompt you to enter the username, email, password for creating superuser. Be sure to enter details you remember.
Start up the server
python manage.py runserver
Navigate to http://localhost:8000/admin/
in your web browser and enter the username and password to login to admin page.
Here you can do create, read, update and delete on TodoModel using admin interface.
Step 2 : Develop our API
In this section, you develop an API endpoint for our model.
Install djangorestframework
and django-cors-headers
pip install djangorestframework django-cors-headers
After installing, add rest_framework
and corsheaders
in settings.py
and update MIDDLEWARE
.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'todo',
'rest_framework',
'corsheaders'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware'
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Add this code in settings.py
CORS_ALLOWED_ORIGINS = [
"http://127.0.0.1:3000",
]
A django-cors-headers is a Python library which prevent a common error caused by CORS rule. In CORS_ALLOWED_ORGINS you list the http://127.0.0.1:3000 because we need our frontend to access Django API.
Start creating serializers
Serializers converts the Django model instance to JSON so that frontend can work with data.
Create todo/serializers.py
and add the following code to the file
from rest_framework import serializers
from .models import TodoModel
class TodoModelSerializer(serializers.ModelSerializer):
class Meta:
model = TodoModel
field = ('id', 'title', 'description', 'completed')
Now we need to create view, navigate to todo/views.py
and update the following code.
from rest_framework import viewsets
from .models import TodoModel
from .serializers import TodoModelSerializer
class TodoView(viewsets.ModelViewSet):
serializer_class = TodoModelSerializer
queryset = TodoModel.objects.all()
viewsets
base class provides a implementation of CRUD by default.
Open backend/urls.py
to update the following snippets
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from todo.views import TodoView
router = routers.DefaultRouter()
router.register('todos', TodoView, 'todo')
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(router.urls))
]
The router enables you to perform CRUD operations
http://127.0.0.1:8000/api/todos/
: returns lists of todo. CREATE
and READ
operations can be performed
http://127.0.0.1:8000/api/todos/:id/
: returns a single todo by using id parameter. UPDATE
and DELETE
operations can be performed.
Restart the server and navigate to http://127.0.0.1:8000/api/todos/
Navigate to http://127.0.0.1:8000/api/todos/:id/
Add 1
to :id
in url to get the todo with id 1
.
Top comments (0)