Startup Kit

Django React Projects: Building an AI SaaS with GPT-4o in 2024

By Patrick on 8/20/2024

Django React Projects: Building an AI SaaS with GPT-4o in 2024

Welcome to the Django React Projects series. For this SaaS app, we’ll walk through creating an AI application using Django, React, and the GPT-4o model.

Project Overview: AI Content Optimizer

We’re building a SaaS that allows users to generate and optimize various types of content using the advanced capabilities of GPT-4o. This project will cover:

  1. Django backend with REST API
  2. React frontend with modern UI components
  3. Integration with OpenAI’s GPT-4o model
  4. User authentication and subscription management
  5. Asynchronous task processing for AI operations

Optimizing content in this context means rewriting it in whatever way the user wants. E.g.

  1. Improving readability
  2. Enhancing SEO
  3. Adjusting tone or style
  4. Expanding on key points
  5. Summarizing lengthy content

Step 1: Setting Up the Django Project

Let’s start by setting up our Django backend:

django-admin startproject ai_content_optimizer
cd ai_content_optimizer
python manage.py startapp api

Install necessary packages:

pip install django djangorestframework django-cors-headers celery redis openai

Update settings.py:

INSTALLED_APPS = [
    # ...
    'rest_framework',
    'corsheaders',
    'api',
]


MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    # ...
]


CORS_ALLOW_ALL_ORIGINS = True  # For development only

These settings enable the Django REST framework and set up CORS headers for seamless communication with our React frontend.

Step 2: Creating Django Models

Define the data structures for our AI Content Optimizer:

from django.db import models
from django.contrib.auth.models import User


class Subscription(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    plan = models.CharField(max_length=20, choices=[
        ('BASIC', 'Basic'),
        ('PRO', 'Professional'),
        ('ENTERPRISE', 'Enterprise'),
    ])
    active = models.BooleanField(default=True)


class ContentOptimizationRequest(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content_type = models.CharField(max_length=50)
    original_content = models.TextField()
    optimized_content = models.TextField(blank=True)
    optimization_params = models.JSONField(default=dict)
    created_at = models.DateTimeField(auto_now_add=True)
    completed_at = models.DateTimeField(null=True, blank=True)

These models allow us to track user subscriptions and content optimization requests, crucial for managing our SaaS platform.

Step 3: Setting Up Django REST Framework

Create serializers and views to expose our data to the React frontend:

# api/serializers.py
from rest_framework import serializers
from .models import ContentOptimizationRequest


class ContentOptimizationRequestSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContentOptimizationRequest
        fields = ['id', 'content_type', 'original_content', 'optimized_content', 'optimization_params', 'created_at', 'completed_at']
        read_only_fields = ['optimized_content', 'completed_at']


# api/views.py
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from .models import ContentOptimizationRequest
from .serializers import ContentOptimizationRequestSerializer
from .tasks import optimize_content


class ContentOptimizationRequestViewSet(viewsets.ModelViewSet):
    serializer_class = ContentOptimizationRequestSerializer
    permission_classes = [IsAuthenticated]


    def get_queryset(self):
        return ContentOptimizationRequest.objects.filter(user=self.request.user)


    def perform_create(self, serializer):
        instance = serializer.save(user=self.request.user)
        optimize_content.delay(instance.id)

This setup creates a RESTful API for our React frontend to interact with.

Step 4: Implementing Celery for Asynchronous Tasks with GPT-4o

Set up a Celery task to handle content optimization using the GPT-4o model:

# api/tasks.py
from celery import shared_task
import openai
from django.utils import timezone
from .models import ContentOptimizationRequest


@shared_task
def optimize_content(request_id):
    request = ContentOptimizationRequest.objects.get(id=request_id)
    
    openai.api_key = 'your-openai-api-key'
    response = openai.ChatCompletion.create(
        model="gpt-4o",  # Using the specialized GPT-4o model
        messages=[
            {"role": "system", "content": "You are an advanced AI assistant specialized in content optimization."},
            {"role": "user", "content": f"Optimize the following {request.content_type} content. Parameters: {request.optimization_params}\n\nContent: {request.original_content}"}
        ],
        max_tokens=1000  # Adjust based on your needs
    )
    
    request.optimized_content = response.choices[0].message['content'].strip()
    request.completed_at = timezone.now()
    request.save()

This task leverages the power of GPT-4o to provide highly optimized content based on user-specified parameters.

Step 5: Setting Up the React Frontend

Create a React application for our user interface:

npx create-react-app frontend
cd frontend
npm install axios react-router-dom @mui/material @emotion/react @emotion/styled

Implement the main component for content optimization:

// src/components/ContentOptimizer.js
import React, { useState } from 'react';
import axios from 'axios';
import { TextField, Button, CircularProgress, Paper, Typography, Select, MenuItem } from '@mui/material';


const ContentOptimizer = () => {
  const [contentType, setContentType] = useState('');
  const [originalContent, setOriginalContent] = useState('');
  const [optimizationParams, setOptimizationParams] = useState({});
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState('');


  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      const response = await axios.post('/api/optimization-requests/', {
        content_type: contentType,
        original_content: originalContent,
        optimization_params: optimizationParams
      });
      setResult(`Optimization request submitted. ID: ${response.data.id}`);
    } catch (error) {
      setResult('Error submitting request');
    }
    setLoading(false);
  };


  return (
    <Paper elevation={3} style={{ padding: '20px', maxWidth: '600px', margin: '20px auto' }}>
      <Typography variant="h5" gutterBottom>AI Content Optimizer</Typography>
      <form onSubmit={handleSubmit}>
        <Select
          fullWidth
          value={contentType}
          onChange={(e) => setContentType(e.target.value)}
          displayEmpty
          margin="normal"
        >
          <MenuItem value="" disabled>Select Content Type</MenuItem>
          <MenuItem value="blog_post">Blog Post</MenuItem>
          <MenuItem value="product_description">Product Description</MenuItem>
          <MenuItem value="social_media_post">Social Media Post</MenuItem>
        </Select>
        <TextField
          fullWidth
          label="Original Content"
          multiline
          rows={6}
          value={originalContent}
          onChange={(e) => setOriginalContent(e.target.value)}
          margin="normal"
        />
        <TextField
          fullWidth
          label="Optimization Parameters (JSON)"
          multiline
          rows={3}
          value={JSON.stringify(optimizationParams)}
          onChange={(e) => setOptimizationParams(JSON.parse(e.target.value))}
          margin="normal"
        />
        <Button type="submit" variant="contained" color="primary" disabled={loading}>
          {loading ? <CircularProgress size={24} /> : 'Optimize Content'}
        </Button>
      </form>
      {result && <Typography style={{ marginTop: '20px' }}>{result}</Typography>}
    </Paper>
  );
};


export default ContentOptimizer;

This React component provides an interface for users to input their content and optimization parameters.

Step 6: Integrating Django and React

Connect the frontend and backend:

# ai_content_optimizer/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from api.views import ContentOptimizationRequestViewSet


router = DefaultRouter()
router.register(r'optimization-requests', ContentOptimizationRequestViewSet, basename='optimization-request')


urlpatterns = [
    path('api/', include(router.urls)),
]

Configure React to proxy requests to Django. In frontend/package.json, add:

"proxy": "http://localhost:8000"

Closing and Callouts

This guide has walked you through creating a Django React project that leverages a django backend and a react frontend. GPT-4o creates a solid foundation for building web applications capable of disrupting traditional industries.

Keep in mind, if you wanted to deploy this to production, you need to make updates to how you do the proxy, cors headers, you’ll need authentication, etc… If you are interested in a production guide, drop me a contact at slimsaas.com and I’ll start working on one!

If you are wanting to focus on building SaaS as fast as possible, check out our kit. It handles all the authentication, payments, styling, etc. so that you can focus on the core idea and bring in that MRR!

Build Faster