Building a CRUD App with Django and React
Why Choose Django and React?
Django is a powerful and scalable web development framework that provides a fast and secure way to build applications. With the power of Python, you can get an application up and running quickly. Meanwhile, React is a popular JavaScript library for building user interfaces. By combining Django and React, you can create a robust and efficient full-stack application.
Getting Started with Django
To begin, make sure you have Python 3, Pip, and NodeJS (version 6 or higher) installed on your machine. Create a new directory for your project and navigate to it in your terminal. Then, create a virtual environment using Python’s built-in venv
feature:
python3 -m venv myenv
Activate the virtual environment and install Django and the required dependencies:
pip install django djangorestframework django-cors-headers
Create a new Django project using the following command:
django-admin startproject django_react_proj
Configuring Django
In the settings.py
file, add the following lines to the INSTALLED_APPS
array:
'django_react_proj.apps.DjangoReactProjConfig',
'rest_framework',
'corsheaders',
Also, add the following lines to the MIDDLEWARE
array:
'corsheaders.middleware.CorsMiddleware',
Creating Models and Views
Create a new app called students
using the following command:
python manage.py startapp students
In the models.py
file, define a Student
model:
“`
from django.db import models
class Student(models.Model):
name = models.CharField(maxlength=255)
email = models.EmailField(unique=True)
createdat = models.DateTimeField(autonowadd=True)
updatedat = models.DateTimeField(autonow=True)
“`
Create a serializer for the Student
model:
“`
from rest_framework import serializers
from.models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = (‘id’, ‘name’, ’email’)
“`
Define views for creating, reading, updating, and deleting students:
“`
from restframework import status
from restframework.response import Response
from rest_framework.views import APIView
from.models import Student
from.serializers import StudentSerializer
class StudentList(APIView):
def get(self, request):
students = Student.objects.all()
serializer = StudentSerializer(students, many=True)
return Response(serializer.data)
def post(self, request):
serializer = StudentSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class StudentDetail(APIView):
def getobject(self, pk):
try:
return Student.objects.get(pk=pk)
except Student.DoesNotExist:
return Response(status=status.HTTP404NOTFOUND)
def get(self, request, pk):
student = self.get_object(pk)
serializer = StudentSerializer(student)
return Response(serializer.data)
def put(self, request, pk):
student = self.get_object(pk)
serializer = StudentSerializer(student, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk):
student = self.get_object(pk)
student.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
“`
Building the React App
Create a new React app using the following command:
npx create-react-app students-fe
Install the required dependencies:
npm install axios bootstrap reactstrap
Create a new file called constants.js
and add the following line:
export const API_URL = 'http://localhost:8000/api/';
Create a new file called Header.js
and add the following code:
“`
import React from ‘eact’;
import { Container, Row, Col } from ‘eactstrap’;
const Header = () => {
return (
Students App
);
};
export default Header;
“`
Create a new file called NewStudentForm.js
and add the following code:
“`
import React, { useState } from ‘eact’;
import { Form, FormGroup, Label, Input, Button } from ‘eactstrap’;
import axios from ‘axios’;
const NewStudentForm = () => {
const [name, setName] = useState(”);
const [email, setEmail] = useState(”);
const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post(`${API_URL}students/`, { name, email });
console.log(response.data);
} catch (error) {
console.error(error);
}
};
return (
<Form onSubmit={handleSubmit}>
<FormGroup>
<Label for="name">Name</Label>
<Input type="text" id="name" value={name} onChange={(event) => setName(event.target.value)} />
</FormGroup>
<FormGroup>
<Label for="email">Email</Label>
<Input type="email" id="email" value={email} onChange={(event) => setEmail(event.target.value)} />
</FormGroup>
<Button type="submit">Create Student</Button>
</Form>
);
};
export default NewStudentForm;
“`
Create a new file called StudentList.js
and add the following code:
“`
import React, { useState, useEffect } from ‘eact’;
import { Table, Thead, Tbody, Tr, Th, Td } from ‘eactstrap’;
import axios from ‘axios’;
const StudentList = () => {
const [students, setStudents] = useState([]);
useEffect(() => {
axios.get(`${API_URL}students/`)
.then(response => {
setStudents(response.data);
})
.catch(error => {
console.error(error);
});
}, []);
return (
<Table>
<Thead>
<Tr>
<Th>Name</Th>
<Th>Email</Th>
<Th>Actions</Th>
</Tr>
</Thead>
<Tbody>
{students.map(student => (
<Tr key={student.id}>
<Td>{student.name}</Td>
<Td>{student.email}</Td>
<Td>
<Button>Edit</Button>
<Button>Delete</Button>
</Td>
</Tr>
))}
</Tbody>
</Table>
);
};
export default StudentList;
“`
Create a new file called App.js
and add the following code:
“`
import React from ‘eact’;
import { Container } from ‘eactstrap’;
import Header from ‘./Header’;
import NewStudentForm from ‘./NewStudentForm’;
import StudentList from ‘./StudentList’;
const App = () => {
return (
);
};
export default App;
“`
Running the App
Start the Django development server:
python manage.py runserver
Start the React app:
npm start
Open your web browser and navigate to http://localhost:3000
to see the app in action.