An Interest In:
Web News this Week
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
- April 17, 2024
Build Web Application using React andDjango
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 upBackend
Open a terminal and enter the following command to create a new project directory.
mkdir todo-django-reactcd todo-django-react
Create an virtual environment and activate it
python -m venv envenv\Scripts\activate
Now, install django
pip install django
Create new project name backend and navigate to folder
django-admin startproject backendcd 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 tododescription
: more details about the individual todocompleted
: it shows the status of todo whether it completed or not
Now run migration to add model to the database
python manage.py makemigrations todopython 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 TodoModeladmin.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 ourAPI
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 serializersfrom .models import TodoModelclass 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 viewsetsfrom .models import TodoModelfrom .serializers import TodoModelSerializerclass 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 adminfrom django.urls import path, includefrom rest_framework import routersfrom todo.views import TodoViewrouter = 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 operationshttp://127.0.0.1:8000/api/todos/
: returns lists of todo. CREATE
and READ
operations can be performedhttp://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
.
Original Link: https://dev.to/ramkumarm15/build-web-application-using-react-and-django-4k40
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To