Task-1 @Catseye Systems, Integrating Django with React for a Family Path Test Application

Author Image

Kaustubh Patil

October 2, 2024 (6mo ago)

Alt text

Introduction

In this post, I’ll share my journey of creating a React application backed by Django for testing family path patterns. My project dynamically handles patient input data and compares virus patterns, offering real-time results while storing information in the Django backend. As someone new to Django, this project has been an exciting challenge.

Tech Stack


1. Setting Up React and Django

To set up the project, I created the React frontend and Django backend separately.

npx create-react-app family-path-test
cd family-path-test

For Django: I created a Django project and app:

django-admin startproject family_test_backend
cd family_test_backend
python manage.py startapp family_test

After that, I installed django-rest-framework to handle the API:

        pip install djangorestframework

2. Dynamic Input Generation in React

In React, the form dynamically adjusts based on the number of patients entered by the user. Each patient gets their own input for the blood sample.

const [numPatients, setNumPatients] = useState(0);
const [patients, setPatients] = useState([]);
 
const handlePatientChange = (index, value) => {
    const updatedPatients = [...patients];
    updatedPatients[index] = value;
    setPatients(updatedPatients);
};
 
return (
    <div>
        <label>Number of Patients:</label>
        <input
            type="number"
            value={numPatients}
            onChange={(e) => {
                setNumPatients(e.target.value);
                setPatients(Array(parseInt(e.target.value)).fill(''));
            }}
        />
        {patients.map((sample, index) => (
            <input
                key={index}
                value={sample}
                onChange={(e) => handlePatientChange(index, e.target.value)}
                placeholder={`Blood Sample ${index + 1}`}
            />
        ))}
    </div>
);

3. Virus Pattern Matching Logic

The main logic involves checking if the virus pattern is a subsequence within each patient's blood sample. The pattern needs to appear in order within the sample.

    let patternIndex = 0;
    for (let char of sample) {
        if (char === pattern[patternIndex]) {
            patternIndex++;
            if (patternIndex === pattern.length) {
                return 'Positive';
            }
        } else if (!pattern.includes(char)) {
            return 'Negative';
        }
    }
    return patternIndex === pattern.length ? 'Positive' : 'Negative';
};

4. Connecting React to Django API

To send the data from React to Django for processing, I used axios to make POST requests. Here’s the code for submitting the data to the API:

    e.preventDefault();
    const logicResults = patients.map(sample => checkPattern(sample, virusPattern));
 
    try {
        const data = { virusPattern, patients };
        await axios.post('http://127.0.0.1:8000/api/family-test/', data);
        setResults(logicResults); // Use the results from local logic
    } catch (error) {
        console.error('Error sending data:', error);
    }
};

On the Django side, I set up an API view to handle this POST request and save the results to the database.

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import FamilyTestResult
 
class FamilyTestView(APIView):
    def post(self, request):
        virus_pattern = request.data.get('virusPattern', '')
        patients = request.data.get('patients', [])
        results = []
        
        for sample in patients:
            result = 'Positive' if virus_pattern in sample else 'Negative'
            FamilyTestResult.objects.create(
                virus_pattern=virus_pattern, patient_sample=sample, result=result
            )
            results.append(result)
        
        return Response({'results': results})

5. Storing Test Results in Django

I used Django’s ORM to store the test results in the database. Here's the model for storing each test result:

from django.db import models
 
class FamilyTestResult(models.Model):
    virus_pattern = models.CharField(max_length=100)
    patient_sample = models.CharField(max_length=255)
    result = models.CharField(max_length=10)
    
    def __str__(self):
        return f'{self.patient_sample} - {self.result}'

6. Reflecting on the Learning Experience

This project was my first experience integrating Django with a React frontend. One of the biggest challenges was understanding how Django REST Framework works and how to structure the API. I also had to manage dynamic form inputs in React, which was a new challenge.

Key Learnings: Understanding how to build a Django API that communicates with a React frontend. Handling dynamic form input in React using hooks and state management. Using Django ORM to store and manage data in a backend database. Overall, this project significantly enhanced my full-stack development skills and confidence in working with Django and React.

Conclusion

Integrating React with Django for this family path test application was a rewarding experience. The dynamic handling of inputs on the frontend combined with the powerful data handling of Django on the backend made it a fun project to work on.