Django React LeadFlow project

LeadFlow (or LeadFlo, if you prefer a shorter name) is a fantastic, simple project for a beginner portfolio because it clearly demonstrates the ability to handle forms, API submission, and data persistence—all critical full-stack skills.

LeadFlow project using React and Django:

📝 LeadFlow Project Breakdown

Goal:

To build a simple system where users can submit contact information (leads) via a React form, and have that data securely saved and viewed via a Django REST API.

1. ⚙️ Backend Setup (Django & DRF)

Model (leads/models.py)

You will need a simple model to represent the submitted data.

# Pseudo-code for models.py

class Lead(models.Model):

    name = models.CharField(max_length=100)

    email = models.EmailField(unique=True)

    message = models.TextField(blank=True, null=True)

    created_at = models.DateTimeField(auto_now_add=True)


Serializer (leads/serializers.py)

This converts the Python object into JSON for the API.

# Pseudo-code for serializers.py

class LeadSerializer(serializers.ModelSerializer):

    class Meta:

        model = Lead

        fields = ('id', 'name', 'email', 'message', 'created_at')


Views (leads/views.py)

Use a generic viewset to handle all API operations easily.

# Pseudo-code for views.py

class LeadViewSet(viewsets.ModelViewSet):

    queryset = Lead.objects.all().order_by('-created_at')

    serializer_class = LeadSerializer

    # Optional: If you add authentication later, you'd add permission classes here.


API Endpoint

 * POST to /api/leads/: Creates a new Lead (used by the React form).

 * GET from /api/leads/: Retrieves all the Leads (for a simple admin viewer).

2. ⚛️ Frontend Setup (React)

Component 1: LeadForm

This component handles user input and API submission.

 * State: Holds the values for name, email, and message.

 * Form: A simple HTML form with corresponding inputs.

 * Action: On submit, use Axios or fetch to send a POST request to your Django endpoint (/api/leads/).

 * Validation: Basic client-side validation (e.g., ensuring the email field is not empty).

Component 2: LeadsList (Optional but Recommended)

A simple component to view the submitted data.

 * Action: On component mount, use Axios or fetch to send a GET request to the endpoint.

 * Display: Render the list of leads in a simple table or list format.

Key Integration Point: CORS

Remember to configure Cross-Origin Resource Sharing (CORS) in your Django settings so that your React app (running on one port, like 3000) can communicate with your Django backend (running on another port, like 8000). You will need the django-cors-headers package.

LeadFlow project bootstrapped with the necessary commands for both the Django API and the React frontend.

🚀 Project Setup Commands

1. Django Backend (API) Setup

We'll use venv for isolated environments and pip for package management.

| Step | Command | Description |

|---|---|---|

| A. Create Project Folder | mkdir LeadFlow | Creates the main project directory. |

| B. Navigate & Init Env | cd LeadFlow and then python -m venv venv | Enters the directory and creates a virtual environment. |

| C. Activate Environment | Linux/macOS: source venv/bin/activate Windows: .\venv\Scripts\activate | Activates the virtual environment. |

| D. Install Dependencies | pip install django djangorestframework django-cors-headers | Installs Django, DRF (for the API), and CORS (to connect React). |

| E. Create Django Project | django-admin startproject leadflow_backend . | Creates the core Django project files (note the .). |

| F. Create Django App | python manage.py startapp leads | Creates the specific application that will handle your Lead model and API. |

| G. Apply Migrations | python manage.py migrate | Sets up the initial database tables (Users, Sessions, etc.). |

2. React Frontend Setup

Assuming you have Node.js and npm/yarn/npx installed, we'll use Vite for a fast setup.

| Step | Command | Description |

|---|---|---|

| A. Create React App | npm create vite@latest leadflow_frontend -- --template react | Creates a new React project using Vite in a separate directory. |

| B. Install Dependencies | cd leadflow_frontend and then npm install axios | Navigates into the React directory and installs Axios (the preferred tool for making API calls). |

| C. Start React Development | npm run dev | Starts the React frontend development server (usually on http://localhost:5173). |

3. Key Configuration Notes

Before you start coding the features, you must complete these two essential steps:

A. Backend Configuration (Django)

In your Django settings file (leadflow_backend/settings.py):

 * Register Apps: Add your new apps to the INSTALLED_APPS list.

   INSTALLED_APPS = [

    # ... existing apps

    'rest_framework',

    'corsheaders',

    'leads',

]


 * Enable CORS: Add corsheaders.middleware.CorsMiddleware to the top of your MIDDLEWARE list.

 * Allow React Origin: Define where your React app will be running (the origin that is allowed to talk to your API).

   CORS_ALLOWED_ORIGINS = [

    "http://localhost:5173", # Update with your actual React dev server port

]


B. Frontend Connection (React)

In your React code, every time you make an API call, you will target the Django server address.

 * API Base URL (e.g., in axios.js or App.jsx): http://localhost:8000/api/leads/

Once you've run these commands, you'll have two separate, connected development environments ready to start implementing the LeadFlow model, serializer, and form components!

Django Model and the React Form component.

1. Django Backend: The Lead Model
This code defines the structure of the data that will be stored in your database.
File: leads/models.py
from django.db import models

class Lead(models.Model):
    # The name of the person submitting the lead
    name = models.CharField(max_length=100)

    # The contact email, set to unique to prevent duplicate submissions
    email = models.EmailField(unique=True)

    # The message or inquiry text (optional)
    message = models.TextField(blank=True, null=True)

    # Automatically records when the lead was submitted
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        # Orders the leads by the newest first by default
        ordering = ['-created_at']

    def __str__(self):
        return f"Lead from {self.name} ({self.email})"

Next Django Steps:
 * Register the Model: Open leads/admin.py and register the model so you can view it in the Django Admin panel:
   from django.contrib import admin
from .models import Lead
admin.site.register(Lead)

 * Make Migrations: In your terminal (with the virtual environment active):
   python manage.py makemigrations leads

 * Apply Migrations:
   python manage.py migrate

2. React Frontend: The LeadForm Component
This component handles the UI, state management, and the crucial API submission.
File: leadflow_frontend/src/LeadForm.jsx (You can create this file directly in src for simplicity)
import React, { useState } from 'react';
import axios from 'axios';

// IMPORTANT: Change this to your actual Django API URL
const API_URL = 'http://localhost:8000/api/leads/';

function LeadForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');
  const [status, setStatus] = useState(''); // For success/error messages

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('Submitting...');

    try {
      const response = await axios.post(API_URL, {
        name,
        email,
        message,
      });

      // Handle successful submission
      console.log('Success:', response.data);
      setStatus('Success! Your lead has been submitted.');
      
      // Clear the form
      setName('');
      setEmail('');
      setMessage('');

    } catch (error) {
      // Handle submission errors (e.g., duplicate email)
      console.error('Submission Error:', error.response ? error.response.data : error.message);
      
      if (error.response && error.response.data.email) {
          setStatus('Error: This email has already been used.');
      } else {
          setStatus('An unexpected error occurred. Please try again.');
      }
    }
  };

  return (
    <div style={{ maxWidth: '400px', margin: '50px auto', padding: '20px', border: '1px solid #ccc', borderRadius: '8px' }}>
      <h2>Submit a Lead</h2>
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '15px' }}>
          <label>Name:</label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
            style={{ width: '100%', padding: '8px', boxSizing: 'border-box' }}
          />
        </div>
        <div style={{ marginBottom: '15px' }}>
          <label>Email:</label>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            style={{ width: '100%', padding: '8px', boxSizing: 'border-box' }}
          />
        </div>
        <div style={{ marginBottom: '15px' }}>
          <label>Message (Optional):</label>
          <textarea
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            rows="4"
            style={{ width: '100%', padding: '8px', boxSizing: 'border-box' }}
          ></textarea>
        </div>
        <button 
            type="submit" 
            style={{ padding: '10px 15px', background: '#007bff', color: 'white', border: 'none', cursor: 'pointer', borderRadius: '4px' }}
        >
          Send Lead
        </button>
      </form>
      {status && <p style={{ marginTop: '15px', color: status.startsWith('Error') ? 'red' : 'green' }}>{status}</p>}
    </div>
  );
}

export default LeadForm;

Next React Steps:
 * Use the Component: Open your main React file (leadflow_frontend/src/App.jsx) and replace the default content with your new form component:
   // leadflow_frontend/src/App.jsx
import LeadForm from './LeadForm'; 

function App() {
  return (
    <div>
      <LeadForm />
    </div>
  )
}

export default App

 * Start Both Servers:
   * Django: Run python manage.py runserver
   * React: Run npm run dev (inside the leadflow_frontend directory)

This is a functional, communicating full-stack application foundation! The final pieces will be creating the Serializer and Views in Django to link the model and the API endpoint URL.

Comments

Popular Posts