KEMBAR78
Django React 2 | PDF | Web Server | Internet & Web
0% found this document useful (0 votes)
19 views19 pages

Django React 2

learn django and reacct

Uploaded by

ndengafranck771
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views19 pages

Django React 2

learn django and reacct

Uploaded by

ndengafranck771
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Full-Stack Web Development Course: React & Django

(Revised)
This course provides a clear, step-by-step path to mastering full-stack web development using
React for dynamic frontends and Django for robust backends. You will learn to build modern
web applications by understanding how these powerful technologies work together.

Course Overview

This revised course is structured into 6 core modules, progressing from foundational setup to
building integrated applications and preparing for deployment.

 Module 1: Getting Started - Setting up your development environment and


understanding the basic project structure for both React and Django.
 Module 2: Django Backend Essentials - Diving into Django's core features: models,
admin, views, URLs, forms, and building powerful REST APIs with Django REST
Framework.
 Module 3: React Frontend Essentials - Mastering React components, state
management, routing, consuming APIs, and styling your applications with a high-level
framework.
 Module 4: Connecting Frontend & Backend - Learning how React and Django
communicate, focusing on authentication using JSON Web Tokens (JWTs).
 Module 5: Building Real-World Applications - Applying your knowledge to build
features common in e-commerce, chat, learning, and inventory management systems.
 Module 6: Deployment & Best Practices - Preparing your application for
production, understanding security, performance, and testing.

Table of Contents

1. Module 1: Getting Started


o 1.1 Introduction to Full-Stack Development
o 1.2 Setting Up Your Development Environment (Python, Node.js, Virtual
Environments)
o 1.3 Initializing Django & React Projects
o 1.4 Basic Project Structure & "Hello World" Integration
o Assignment 1.1: Setup & First API Call
2. Module 2: Django Backend Essentials
o 2.1 Data Management with Django Models (ORM)
o 2.2 Django Admin: Your Built-in Content Manager
o 2.3 Handling Web Requests: Views & URLs
o 2.4 Building RESTful APIs with Django REST Framework (DRF)
o Assignment 2.1: Simple API for a Product Catalog
3. Module 3: React Frontend Essentials
o 3.1 Building User Interfaces with React Components & State
o 3.2 Dynamic Behavior with React Hooks (useState, useEffect)
o 3.3 Navigation with React Router
o 3.4 Styling Your App with a Framework (Bootstrap/Tailwind CSS)
o 3.5 Fetching Data from APIs
o Assignment 3.1: Product Catalog Frontend
4. Module 4: Full-Stack Integration & Authentication
o 4.1 Understanding Cross-Origin Resource Sharing (CORS)
o 4.2 Implementing User Authentication with JWT
o 4.3 Protecting API Endpoints & Frontend Routes
o Assignment 4.1: User Login & Protected Products
5. Module 5: Building Real-World Applications
o 5.1 E-commerce: Shopping Cart & Order Flow
o 5.2 Real-time Chat: Introduction to Django Channels & WebSockets
o 5.3 Learning Systems: Courses, Lessons & Progress
o 5.4 Inventory Management: Stock Tracking & Transactions
o Assignment 5.1: Add a Core Feature to Your Product App
6. Module 6: Deployment & Best Practices
o 6.1 Preparing for Production: Static Files & Media
o 6.2 Deploying Your Application (Gunicorn, Nginx, Environment Variables)
o 6.3 Security Fundamentals (XSS, CSRF, SQLi)
o 6.4 Testing & Debugging Your Full-Stack App
o Assignment 6.1: Basic Deployment Simulation
7. Assignments & Solutions (Conceptual)
o Conceptual Answers for all Assignments
8. End-of-Course Projects (5 Ideas)
o Project Ideas with Completion Criteria

1. Module 1: Getting Started

1.1 Introduction to Full-Stack Development

 What is Full-Stack? Understanding the roles of frontend (what users see) and
backend (server logic, data).
 Why React & Django? Strengths of React for dynamic UIs and Django for robust,
"batteries-included" backends.
 RESTful APIs: The standard way frontend and backend communicate.
 Development Workflow: Running separate development servers for each part.

1.2 Setting Up Your Development Environment

 Python 3.x: Installation and verification (python3 --version).


 pip: Python's package installer (pip3 --version).
 Virtual Environments: Creating (python3 -m venv venv), activating (source
venv/bin/activate or .\venv\Scripts\activate), and why they're essential for
dependency management.
 Node.js & npm/Yarn: Installation and purpose for React (node -v, npm -v).

1.3 Initializing Django & React Projects

 Django Project:
o pip install Django django-cors-headers djangorestframework
djangorestframework-simplejwt
o django-admin startproject myproject . (creates project in current
directory)
 React Project:
o npx create-react-app frontend (creates a frontend folder with React
app)
o cd frontend
o npm install bootstrap react-bootstrap (for Bootstrap) OR npm
install -D tailwindcss postcss autoprefixer and configure (for
Tailwind).

1.4 Basic Project Structure & "Hello World" Integration

 Overall Structure: A root folder containing backend/ (Django) and frontend/


(React).
 Django Backend Setup:
o Create a Django app: python manage.py startapp api
o Add api, rest_framework, corsheaders, rest_framework_simplejwt to
INSTALLED_APPS in myproject/settings.py.
o Configure CORS_ALLOWED_ORIGINS in settings.py to allow your React dev
server (e.g., ['http://localhost:3000']).
o Create a simple API view in api/views.py that returns {"message": "Hello
from Django!"}.
o Map this view to a URL (e.g., /api/hello/) in api/urls.py and include it in
myproject/urls.py.
o Run Django dev server: python manage.py runserver.
 React Frontend Setup:
o In frontend/src/App.js, write code to fetch the JSON message from your
Django backend (http://127.0.0.1:8000/api/hello/) using fetch or
Axios.
o Display the message in your React component.
o Run React dev server: npm start.

Assignment 1.1: Setup & First API Call

1. Create a new root project directory (e.g., my_fullstack_app).


2. Inside it, create backend/ and frontend/ subdirectories.
3. Backend:
o Set up a Python virtual environment in backend/.
o Install all necessary Django and DRF packages.
o Create a Django project named core and an app named hello_api.
o Configure settings.py to include the app and CORS settings for
http://localhost:3000.
o Create a view in hello_api/views.py that returns {"status": "success",
"data": "Hello from Django Backend!"}.
o Map this view to /api/greeting/ in hello_api/urls.py and include it in
core/urls.py.
o Run python manage.py runserver.
4. Frontend:
o Navigate to frontend/ and create a new React app.
o In frontend/src/App.js, use useEffect to make a GET request to
http://127.0.0.1:8000/api/greeting/.
o Display the data message from the response on the screen. Include basic
loading and error messages.
o Run npm start.
5. Verification: Confirm that your React app successfully displays "Hello from Django
Backend!".

2. Module 2: Django Backend Essentials

2.1 Data Management with Django Models (ORM)

 Django's ORM: How it maps Python classes to database tables.


 Defining Models: Creating models.py classes with models.Model.
 Field Types: Common fields like CharField, TextField, IntegerField,
DecimalField, DateTimeField, BooleanField.
 Relationships: ForeignKey (one-to-many), ManyToManyField (many-to-many),
OneToOneField (one-to-one).
 Migrations: python manage.py makemigrations (detect changes) and python
manage.py migrate (apply changes to DB).
 Basic CRUD Operations: Using the Django shell (python manage.py shell) to
create, retrieve, update, and delete objects.

2.2 Django Admin: Your Built-in Content Manager

 Automatic Admin Panel: Django's powerful, ready-to-use admin interface.


 Creating a Superuser: python manage.py createsuperuser to gain admin access.
 Registering Models: Making your custom models visible in the admin
(admin.site.register() or @admin.register).
 Customizing the Admin: Using ModelAdmin options (list_display, list_filter,
search_fields) to improve usability.

2.3 Handling Web Requests: Views & URLs

 Views: Python functions or classes that receive web requests and return responses.
o Function-Based Views (FBVs): Simple functions (def my_view(request):
...).
o Class-Based Views (CBVs): More structured, often used with Django's
generic views (ListView, DetailView, CreateView, UpdateView,
DeleteView) for common patterns.
 URLs: Mapping web addresses to your views.
o path(): The primary way to define URL patterns.
o include(): For modularizing URL configurations across apps.
o URL Names: Using name argument for reverse lookups ({% url
'app_name:url_name' %}).

2.4 Building RESTful APIs with Django REST Framework (DRF)

 Introduction to DRF: Why DRF is the standard for building APIs in Django.
 Serializers: Converting Django models into JSON (serialization) and converting
incoming JSON into Python objects (deserialization).
rest_framework.serializers.ModelSerializer.
 API Views:
o @api_view decorator for FBVs.
o APIView for basic CBVs.
o generics.* views (e.g., ListAPIView, RetrieveAPIView,
ListCreateAPIView) for common API patterns.
 ViewSets & Routers: Simplifying API creation for full CRUD operations
(viewsets.ModelViewSet) and automatically generating URL patterns.

Assignment 2.1: Simple API for a Product Catalog

1. Models: In your backend/api/models.py, define a Product model with fields like


name (CharField), description (TextField), price (DecimalField), stock
(IntegerField), is_available (BooleanField), and created_at (DateTimeField,
auto_now_add=True).
2. Migrations: Run makemigrations and migrate.
3. Admin: Register the Product model in backend/api/admin.py. Create a superuser
and add at least 5 sample products via the Django Admin.
4. Serializers: Create backend/api/serializers.py with a ProductSerializer
using rest_framework.serializers.ModelSerializer.
5. API Views: In backend/api/views.py, create a ProductViewSet using
rest_framework.viewsets.ModelViewSet. Set its queryset to
Product.objects.all() and serializer_class to ProductSerializer.
6. URLs: In backend/api/urls.py, use a DefaultRouter from
rest_framework.routers to register your ProductViewSet. Include these API
URLs in your project's backend/core/urls.py (e.g., /api/products/).
7. Test: Run python manage.py runserver. Use your web browser or a tool like
Postman to test:
o GET http://127.0.0.1:8000/api/products/ (should list all products).
o GET http://127.0.0.1:8000/api/products/1/ (should show details for
product with ID 1).

3. Module 3: React Frontend Essentials

3.1 Building User Interfaces with React Components & State

 Functional Components: The modern way to write React components.


 JSX: Writing HTML-like syntax within JavaScript.
 Props: Passing data from parent components to child components.
 State: Managing data that changes over time within a component using useState.

3.2 Dynamic Behavior with React Hooks (useState, useEffect)

 useState: Review for managing component state.


 useEffect: Performing side effects (like data fetching,
subscriptions, manual DOM
manipulation). Understanding the dependency array to control when effects run.
 Conditional Rendering: Displaying different parts of the UI based on conditions.
 List Rendering: Efficiently displaying collections of data using map().

3.3 Navigation with React Router

 Installation: npm install react-router-dom.


 BrowserRouter, Routes, Route: Setting up client-side routing for single-page
applications.
 Link component: Navigating between pages without full page reloads.
 URL Parameters: Extracting dynamic data from the URL (e.g., product ID from
/products/:id).

3.4 Styling Your App with a Framework (Bootstrap/Tailwind CSS)

 Introduction to CSS Frameworks: Benefits of using pre-built components and


utility classes for rapid development and consistent design.
 Bootstrap:
o Installation: npm install bootstrap react-bootstrap.
o Using React-Bootstrap components (e.g., Container, Row, Col, Card, Button,
Form).
o Responsive design using Bootstrap's grid system and utility classes.
 Tailwind CSS:
o Installation & Configuration: Setting up tailwind.config.js and
postcss.config.js.
o Utility-first approach: Building designs directly in JSX using small,
composable utility classes (e.g., flex, grid, p-4, shadow-md, rounded-lg).
o Responsive design using Tailwind's breakpoint prefixes (sm:, md:, lg:).
 Choosing a Framework: Discussing the trade-offs (opinionated vs. unopinionated,
component-based vs. utility-first).

3.5 Fetching Data from APIs

 fetch API: The browser's built-in way to make HTTP requests.


 Axios: A popular third-party library for making HTTP requests, often preferred for its
features like interceptors and better error handling.
 Handling Asynchronous Data: Using async/await syntax for cleaner asynchronous
code.
 Loading & Error States: Implementing UI feedback (spinners, error messages) while
data is being fetched or if an error occurs.

Assignment 3.1: Product Catalog Frontend

1. Setup: Ensure your React app is ready. Install your chosen styling framework
(Bootstrap or Tailwind CSS) and react-router-dom.
2. Routing: Set up React Router to have at least two main pages:
o /: A ProductListPage component.
o /products/:id: A ProductDetailPage component.
3. API Consumption:
o In ProductListPage, use useEffect to fetch all products from your Django
backend's /api/products/ endpoint.
o Display the products using your chosen styling framework (e.g., as cards in a
grid). Each product card should show its name, price, and a "View Details"
button/link that navigates to its ProductDetailPage (e.g., /products/1).
o In ProductDetailPage, use useEffect and URL parameters (useParams
from React Router) to fetch a single product from /api/products/:id/.
o Display the full product details (name, description, price, stock) on this page,
styled appropriately.
4. State Management: Use useState to manage the list of products, the single product
details, loading indicators, and any error messages.
5. Styling: Make sure your product list and detail pages are visually appealing and
responsive using your chosen framework's classes/components.

4. Module 4: Full-Stack Integration & Authentication

4.1 Understanding Cross-Origin Resource Sharing (CORS)

 The Same-Origin Policy: Why browsers restrict requests between different origins
(domain, protocol, port).
 CORS Headers: How the server tells the browser it's safe to allow cross-origin
requests.
 django-cors-headers: Review its installation and configuration in settings.py
(CORS_ALLOWED_ORIGINS, CORS_ALLOW_ALL_ORIGINS).
 Debugging CORS: Common errors and how to resolve them.

4.2 Implementing User Authentication with JWT (JSON Web Tokens)

 JWT Basics: What a JWT is (header, payload, signature), how it provides stateless
authentication for APIs.
 djangorestframework-simplejwt:
o Review its installation and configuration in settings.py.
o Understanding the default JWT endpoints: /api/token/ (for obtaining tokens)
and /api/token/refresh/ (for getting new access tokens).
 Authentication Flow:
1. User sends username/password to Django login endpoint.
2. Django validates credentials and returns access and refresh tokens.
3. React stores tokens (e.g., in localStorage).
4. React sends the access token in the Authorization: Bearer <token> header
for protected API requests.
 React Authentication Context: Creating a global AuthContext to manage the user's
login status and tokens across your React application.
 Token Refresh: Implementing logic to automatically refresh an expired access token
using the refresh token.

4.3 Protecting API Endpoints & Frontend Routes

 Backend (DRF Permissions): Using


rest_framework.permissions.IsAuthenticated or custom permissions to restrict
access to Django API views.
 Frontend (React Router Guards): Creating wrapper components or custom hooks to
protect React routes, redirecting unauthenticated users to a login page.
 Conditional UI: Showing/hiding UI elements (e.g., "Create Product" button) based on
user authentication status.

Assignment 4.1: User Login & Protected Products

1. Backend (Django):
o Ensure djangorestframework-simplejwt is fully configured in
settings.py and its URLs are included.
o Modify your ProductViewSet in backend/api/views.py to require
authentication for POST, PUT, PATCH, DELETE operations (e.g.,
permission_classes = [IsAuthenticated]). GET operations can remain
public.
o (Optional but recommended) Create a simple user registration endpoint in
backend/api/views.py (e.g., a UserCreateAPIView or a custom view that
uses Django's UserCreationForm or a custom serializer).
2. Frontend (React):
o Create Login.js and Register.js components with forms.
o Implement logic to send user credentials to Django's /api/token/ (for login)
and your registration endpoint (for register).
o On successful login, store the received access and refresh tokens in
localStorage.
o Create an AuthContext (using createContext and useContext) to provide
currentUser data (e.g., id, username) and login/logout functions
throughout your app.
o Wrap your App component with the AuthContext.Provider.
o Modify your API calls (e.g., using Axios interceptors) to include the
Authorization: Bearer <access_token> header for all requests to your
Django API.
o Implement a "Logout" button in your UI that clears tokens and updates the
AuthContext.
o Protected Frontend Route: Use React Router to protect a route (e.g.,
/products/create). If the user is not authenticated, redirect them to the
/login page.
o Conditional UI: Show a "Create New Product" button on the
ProductListPage only if the user is logged in.

5. Module 5: Building Real-World Applications

This module focuses on applying your full-stack knowledge to build core features found in
various types of web applications. You will extend your existing product catalog application
or start new minimal setups to implement these features.

5.1 E-commerce: Shopping Cart & Order Flow

 Backend (Django Models & APIs):


o Extend Product model.
o New Models: Cart (user, created_at), CartItem (cart, product, quantity),
Order (user, status, total_price, shipping_address), OrderItem (order, product,
quantity, price_at_purchase).
o DRF APIs:
 Cart management (add/remove items, update quantity).
 Order creation from cart.
 Order history for users.
o Conceptual: Payment gateway integration (Stripe/PayPal) – focus on backend
handling of secret keys and API calls.
 Frontend (React Components & Logic):
o "Add to Cart" buttons on product pages/listings.
o Dedicated CartPage to display items, allow quantity changes, and remove
items.
o CheckoutPage: Collecting shipping info, displaying order summary, simulated
payment button.
o OrderHistoryPage: Displaying a user's past orders.
o State Management: Using React Context or a simple global state for the
shopping cart.

5.2 Real-time Chat: Introduction to Django Channels & WebSockets

 Backend (Django Channels):


o ASGI: Understanding Django's asynchronous capabilities.
o Django Channels: Installation (pip install channels channels_redis)
and configuration (ASGI_APPLICATION, CHANNEL_LAYERS).
o Consumers: Asynchronous functions/classes that handle WebSocket
connections and messages.
o Channels Layers: For broadcasting messages to multiple clients (e.g., Redis
backend).
o Models: ChatRoom (name), ChatMessage (room, sender, content, timestamp).
o Routing: Mapping WebSocket URLs to Consumers.
 Frontend (React Components & Logic):
o Establishing a WebSocket connection to the Django Channels backend.
o Real-time message display: Updating the chat UI instantly as messages arrive.
o Sending messages: Sending JSON data over the WebSocket.
o UI for selecting chat rooms or direct messages.

5.3 Learning Systems: Courses, Lessons & Progress

 Backend (Django Models & APIs):


o Models: Course (title, description, instructor (ForeignKey to User)), Lesson
(course, title, content, order), Enrollment (user, course, progress,
completed_lessons).
o DRF APIs:
 Course listing and detail.
 Lesson content retrieval.
 Enrollment management.
 Progress tracking (e.g., marking a lesson as complete).
o User Roles: Differentiating between 'Student' and 'Instructor' (using Django's
built-in permissions or a custom User model extension).
 Frontend (React Components & Logic):
o CourseCatalogPage: Displaying available courses.
o CourseDetailPage: Viewing course details, enrollment button.
o LessonViewerPage: Displaying lesson content, "Mark Complete" button.
o DashboardPage: Showing enrolled courses and overall progress.

5.4 Inventory Management: Stock Tracking & Transactions

 Backend (Django Models & APIs):


o Models: Item (name, SKU, quantity_in_stock, reorder_point, description),
Location (name, address), Transaction (item, type (IN/OUT), quantity,
timestamp, user).
o DRF APIs:
 Item listing, detail, CRUD operations.
 API for recording stock adjustments (in/out transactions).
 Transaction history.
 Simple reporting (e.g., low stock items).
 Frontend (React Components & Logic):
o Dashboard: Overview of stock levels, alerts for low stock.
o ItemManagementPage: Table of items, forms for adding/editing/deleting items.
o StockAdjustmentForm: Form for recording incoming or outgoing stock.
o TransactionHistoryPage: Displaying a list of all inventory transactions.

Assignment 5.1: Add a Core Feature to Your Product App

Choose one of the following features and integrate it into your existing React/Django Product
Catalog application from previous assignments.

1. Shopping Cart (E-commerce):


o Backend: Add Cart and CartItem models. Create DRF APIs for GET (user's
cart), POST (add item to cart), PUT (update item quantity), and DELETE (remove
item from cart). Ensure these are protected by authentication.
o Frontend: Add an "Add to Cart" button on the ProductDetailPage. Create a
CartPage component that fetches the user's cart from the backend, displays
items, and allows quantity adjustments or item removal. Add a "Checkout"
button (which can just display a success message for now).
2. Product Reviews (E-commerce/Social):
o Backend: Add a Review model (product, user, rating, comment, timestamp).
Create DRF APIs for creating, listing, and potentially updating/deleting
reviews.
o Frontend: On the ProductDetailPage, display existing reviews. If the user is
logged in, provide a form to submit a new review.
3. Simple Chat for Product Inquiries (ChatApp Concept):
o Backend: Install Django Channels. Create InquiryChatRoom (product, user)
and InquiryMessage (room, sender, content, timestamp) models. Implement a
basic Consumer to handle WebSocket connections for these inquiry rooms.
o Frontend: On the ProductDetailPage, add a "Chat with Seller" button (or
similar). This opens a simple chat interface (a modal or new route) that
connects via WebSocket to the Django Channels backend for real-time
messaging about that specific product.

6. Module 6: Deployment & Best Practices


6.1 Preparing for Production: Static Files & Media

 collectstatic: Understanding how python manage.py collectstatic gathers all


static files (CSS, JS, images) into a single directory (STATIC_ROOT) for efficient
serving.
 Serving Static Files in Production: Why your web server (Nginx/Apache) should
serve these files directly, not Django.
 Media Files: Handling user-uploaded files (MEDIA_ROOT, MEDIA_URL).
 Cloud Storage: Introduction to using cloud storage services (like AWS S3, Google
Cloud Storage) for static and media files in large-scale applications.

6.2 Deploying Your Application (Gunicorn, Nginx, Environment Variables)

 WSGI Server (Gunicorn): Flask's built-in server is for development only. Gunicorn
is a production-ready WSGI HTTP server for Python applications.
o Running Gunicorn: gunicorn myproject.wsgi:application --bind
0.0.0.0:8000.
 Reverse Proxy (Nginx): Nginx sits in front of Gunicorn.
o Purpose: Serves static/media files, handles SSL/TLS (HTTPS), load
balancing, and acts as a security layer.
o Configuration: Basic Nginx setup to proxy API requests to Gunicorn and
serve static/media files.
 Environment Variables: Crucial for managing sensitive data (database credentials,
SECRET_KEY, API keys) and configuration settings in production.
o Using python-dotenv for local development.
o Setting variables directly on the production server or via platform-specific
mechanisms.

6.3 Security Fundamentals (XSS, CSRF, SQLi)

 Review of Vulnerabilities: Cross-Site Scripting (XSS), Cross-Site Request Forgery


(CSRF), SQL Injection.
 Django's Built-in Protections: How Django's ORM, {% csrf_token %}, and
template auto-escaping protect against common attacks.
 React Security: Preventing XSS by default (React escapes content), and
understanding when manual sanitization is needed (e.g., dangerouslySetInnerHTML).
 HTTPS: The importance of always using HTTPS in production to encrypt all data in
transit.
 Security Headers: Using Django extensions like django-csp or django-talisman
to add HTTP security headers (e.g., Content Security Policy, X-Frame-Options).

6.4 Testing & Debugging Your Full-Stack App

 Testing:
o Unit Tests: Testing individual components or functions in isolation (e.g.,
Django models, React components).
o Integration Tests: Testing how different parts of your application interact
(e.g., Django API endpoints with mock data, React components interacting
with a mocked API).
o Using Django's TestCase and Client for backend tests.
o Using React Testing Library for frontend tests.
 Debugging:
o Using Python debuggers (e.g., pdb, VS Code debugger) for the backend.
o Using browser developer tools and React DevTools for the frontend.
o Effective logging practices.

Assignment 6.1: Basic Deployment Simulation

1. Prepare your Product Catalog application: Ensure your Django backend and React
frontend are working correctly in development.
2. Backend (Django):
o In backend/myproject/settings.py, set DEBUG = False.
o Set ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] (for local simulation,
or your server's IP/domain if deploying for real).
o Run python manage.py collectstatic.
o Install Gunicorn: pip install gunicorn.
o Simulate Gunicorn running: gunicorn myproject.wsgi:application --
bind 127.0.0.1:8000. Keep this running in one terminal.
3. Frontend (React):
o In your frontend directory, create a production build: npm run build. This
creates a build/ folder with optimized static files.
o Option A (Serve React via Django):
 Modify backend/myproject/settings.py to point
STATICFILES_DIRS to your React build folder (e.g.,
os.path.join(BASE_DIR, '../frontend/build/static')).
 Add a catch-all URL in backend/myproject/urls.py to serve
index.html for all non-API routes (e.g., re_path(r'^.*',
TemplateView.as_view(template_name='index.html'))).
 Ensure index.html from your React build is accessible to Django's
template loader (you might need to copy it or adjust
TEMPLATES['DIRS']).
 Run python manage.py runserver (or Gunicorn) and access
http://127.0.0.1:8000/.
o Option B (Serve React via a simple HTTP server):
 Install a simple HTTP server (e.g., npm install -g serve).
 Navigate to your frontend/build directory.
 Run serve -s . -l 3000.
 Access http://localhost:3000/ in your browser. (Ensure your
Django backend is still running on 8000).
4. Verification: Confirm that your application loads and functions correctly in a
simulated production setup. Check the browser console for any errors related to static
files or API calls.

7. Assignments & Solutions (Conceptual)

This section provides conceptual answers to the assignments. These are outlines of the
expected approach and key components, not full code implementations.

Assignment 1.1: Setup & First API Call


 Backend:
o backend/core/settings.py: INSTALLED_APPS = ['hello_api',
'corsheaders', 'rest_framework', 'rest_framework_simplejwt'],
MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware', ...],
CORS_ALLOWED_ORIGINS = ['http://localhost:3000'].
o backend/hello_api/views.py: from rest_framework.response import
Response; from rest_framework.decorators import api_view;
@api_view(['GET']) def greeting_view(request): return
Response({"status": "success", "data": "Hello from Django
Backend!"}).
o backend/hello_api/urls.py: from django.urls import path; from .
import views; urlpatterns = [path('greeting/',
views.greeting_view, name='greeting')].
o backend/core/urls.py: from django.urls import path, include;
urlpatterns = [path('api/', include('hello_api.urls'))].
 Frontend:
o frontend/.env: REACT_APP_API_URL=http://127.0.0.1:8000/api.
o frontend/src/App.js:
o import React, { useState, useEffect } from 'react';
o function App() {
o const [message, setMessage] = useState('Loading...');
o const [error, setError] = useState(null);
o useEffect(() => {
o fetch(`${process.env.REACT_APP_API_URL}/greeting/`)
o .then(response => {
o if (!response.ok) throw new Error('Network response was
not ok.');
o return response.json();
o })
o .then(data => setMessage(data.data))
o .catch(error => setError(error.message));
o }, []);
o return (
o <div>
o <h1>React App</h1>
o {error ? <p style={{color: 'red'}}>Error: {error}</p> :
<p>{message}</p>}
o </div>
o );
o }
o export default App;

Assignment 2.1: Simple API for a Product Catalog

 Models (backend/api/models.py):
 from django.db import models
 class Product(models.Model):
 name = models.CharField(max_length=255)
 description = models.TextField(blank=True, null=True)
 price = models.DecimalField(max_digits=10, decimal_places=2)
 stock = models.IntegerField(default=0)
 is_available = models.BooleanField(default=True)
 created_at = models.DateTimeField(auto_now_add=True)
 def __str__(self): return self.name
 Migrations: python manage.py makemigrations api, python manage.py
migrate.
 Admin (backend/api/admin.py): from django.contrib import admin; from
.models import Product; admin.site.register(Product).
 Serializers (backend/api/serializers.py):
 from rest_framework import serializers
 from .models import Product
 class ProductSerializer(serializers.ModelSerializer):
 class Meta:
 model = Product
 fields = '__all__'

 API Views (backend/api/views.py):


 from rest_framework import viewsets
 from .models import Product
 from .serializers import ProductSerializer
 class ProductViewSet(viewsets.ModelViewSet):
 queryset = Product.objects.all().order_by('name')
 serializer_class = ProductSerializer

 URLs (backend/api/urls.py):
 from django.urls import path, include
 from rest_framework.routers import DefaultRouter
 from .views import ProductViewSet
 router = DefaultRouter()
 router.register(r'products', ProductViewSet)
 urlpatterns = [path('', include(router.urls))]

 Project URLs (backend/core/urls.py): path('api/', include('api.urls')).

Assignment 3.1: Product Catalog Frontend

 Routing (frontend/src/App.js):
 import { BrowserRouter as Router, Routes, Route, Link } from 'react-
router-dom';
 // ... import ProductListPage, ProductDetailPage
 function App() {
 return (
 <Router>
 <nav> <Link to="/">Products</Link> </nav>
 <Routes>
 <Route path="/" element={<ProductListPage />} />
 <Route path="/products/:id" element={<ProductDetailPage />}
/>
 </Routes>
 </Router>
 );
 }
 ProductListPage (frontend/src/components/ProductListPage.js):
o useState for products, loading, error.
o useEffect to fetch products from REACT_APP_API_URL/products/.
o Map products to ProductCard components.
o Use Bootstrap Container, Row, Col, Card or Tailwind grid, gap-4, shadow-
md for styling.
 ProductDetailPage (frontend/src/components/ProductDetailPage.js):
o useParams to get id.
o useState for product, loading, error.
o useEffect to fetch product from REACT_APP_API_URL/products/${id}/.
o Display details. Use Bootstrap Card or Tailwind p-6, rounded-lg.

Assignment 4.1: User Login & Protected Products

 Backend:
o settings.py: Add DEFAULT_AUTHENTICATION_CLASSES to REST_FRAMEWORK
settings:
('rest_framework_simplejwt.authentication.JWTAuthentication',).
o backend/core/urls.py: Add path('api/token/',
TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(),
name='token_refresh').
o backend/api/views.py: In ProductViewSet, add permission_classes =
[IsAuthenticatedOrReadOnly] for GET and [IsAuthenticated] for
POST/PUT/DELETE.
o (Optional Register View):
o # backend/api/views.py
o from django.contrib.auth.models import User
o from rest_framework import generics, permissions
o from .serializers import UserSerializer # Create a
UserSerializer
o class RegisterView(generics.CreateAPIView):
o queryset = User.objects.all()
o permission_classes = (permissions.AllowAny,)
o serializer_class = UserSerializer
o # backend/api/urls.py: path('register/',
RegisterView.as_view(), name='register')

 Frontend:
o AuthContext.js:
o import React, { createContext, useState, useEffect, useContext
} from 'react';
o const AuthContext = createContext(null);
o export const AuthProvider = ({ children }) => {
o const [authToken, setAuthToken] =
useState(localStorage.getItem('access_token'));
o const [refreshToken, setRefreshToken] =
useState(localStorage.getItem('refresh_token'));
o const [user, setUser] = useState(null);
o // ... login, logout functions, useEffect to set user from
token ...
o return (<AuthContext.Provider value={{ authToken,
refreshToken, user, login, logout
}}>{children}</AuthContext.Provider>);
o };
o export const useAuth = () => useContext(AuthContext);

o Login.js, Register.js: Forms to post to Django's /api/token/ or


/api/register/. On success, store tokens in localStorage and update
AuthContext.
o Axios Interceptor (frontend/src/api.js):
o import axios from 'axios';
o const api = axios.create({ baseURL:
process.env.REACT_APP_API_URL });
o api.interceptors.request.use(config => {
o const token = localStorage.getItem('access_token');
o if (token) { config.headers.Authorization = `Bearer
${token}`; }
o return config;
o });
o // ... add response interceptor for token refresh ...
o export default api;

o Protected Route (frontend/src/components/ProtectedRoute.js):


o import React from 'react';
o import { Navigate, Outlet } from 'react-router-dom';
o import { useAuth } from '../context/AuthContext';
o const ProtectedRoute = () => {
o const { authToken } = useAuth();
o return authToken ? <Outlet /> : <Navigate to="/login" replace
/>;
o };
o export default ProtectedRoute;

o App.js: Use <Route element={<ProtectedRoute />}> for protected routes.


Conditionally render "Create New Product" button based on
useAuth().authToken.

Assignment 5.1: Add a Core Feature to Your Product App (Example: Shopping Cart)

 Backend:
o models.py: Cart (ForeignKey to User), CartItem (ForeignKey to Cart,
ForeignKey to Product, IntegerField quantity).
o serializers.py: CartItemSerializer, CartSerializer (includes nested
CartItemSerializer).
o views.py: CartViewSet with retrieve, add_item (custom action),
update_item, remove_item methods. Protected by IsAuthenticated.
o urls.py: Register CartViewSet with router, and add custom action routes.
 Frontend:
o CartContext.js: Manages cart state (items, total). Functions for addToCart,
removeFromCart, updateQuantity. Fetches/sends cart data to backend.
o ProductDetailPage: "Add to Cart" button, calls CartContext.addToCart.
o CartPage.js: Displays cart items, allows quantity/removal. Fetches cart from
backend via CartContext.
o Styling: Use Bootstrap Table, Button, Modal or Tailwind table, flex, grid
for cart UI.

Assignment 6.1: Basic Deployment Simulation

 Backend:
o settings.py: DEBUG = False, ALLOWED_HOSTS = ['127.0.0.1'].
o python manage.py collectstatic.
o Run Gunicorn: gunicorn myproject.wsgi:application --bind
127.0.0.1:8000.
 Frontend:
o npm run build.
o Option A (Django serving React):
 backend/myproject/settings.py:
 import os
 # ...
 STATICFILES_DIRS = [
 os.path.join(BASE_DIR, '../frontend/build/static'), #
Point to React's static files
 ]
 TEMPLATES = [
 {
 'DIRS': [os.path.join(BASE_DIR,
'../frontend/build')], # Point to React's index.html
 # ...
 },
 ]

 backend/core/urls.py:
 from django.urls import path, re_path, include
 from django.views.generic import TemplateView
 # ...
 urlpatterns = [
 # ... your API paths ...
 re_path(r'^(?:.*)/?$',
TemplateView.as_view(template_name='index.html')), #
Catch-all for React routes
 ]

 Run Gunicorn and access http://127.0.0.1:8000/.


o Option B (Separate HTTP server for React):
 cd frontend/build
 npx serve -s . -l 3000
 Access http://localhost:3000/.

Assignment 7.1: Security Review & Testing

 Audit:
o settings.py: Confirm DEBUG=False in production, SECRET_KEY is long and
random, ALLOWED_HOSTS is specific.
o Forms: Check all POST forms (Django templates or React forms sending POST
requests) include {% csrf_token %} (for Django templates) or handle CSRF
token in React (if not using JWT only).
o Data rendering: Search for mark_safe in Django templates or
dangerouslySetInnerHTML in React and verify proper sanitization is applied
if user-generated content is involved.
o Database queries: Ensure no raw SQL queries are used with unsanitized user
input.
 Testing:
o Django test:
o from django.test import TestCase, Client
o from django.urls import reverse
o # ... import User, Product, etc.
o class ProductAPISecurityTest(TestCase):
o def setUp(self):
o self.client = Client()
o self.product_data = {'name': 'Test Product', 'price':
10.00, 'stock': 5}
o # ... create a test user, get a JWT token for them ...
o def test_create_product_unauthenticated(self):
o response = self.client.post(reverse('api:product-
list'), self.product_data, content_type='application/json')
o self.assertEqual(response.status_code, 401) #
Unauthorized
o def test_create_product_with_invalid_token(self):
o response = self.client.post(reverse('api:product-
list'), self.product_data, content_type='application/json',
HTTP_AUTHORIZATION='Bearer invalidtoken')
o self.assertEqual(response.status_code, 401) #
Unauthorized
o # ... test authenticated creation ...

o React test:
o import { render, screen } from '@testing-library/react';
o import ProductListPage from '../components/ProductListPage';
o import { AuthProvider } from '../context/AuthContext'; // If
testing with context
o test('renders product list page with loading message
initially', () => {
o render(<AuthProvider><ProductListPage /></AuthProvider>);
o expect(screen.getByText(/loading
products/i)).toBeInTheDocument();
o });

 Security Header:
o pip install django-csp.
o settings.py: Add 'csp.middleware.CSPMiddleware' to MIDDLEWARE.
o Configure CSP_DEFAULT_SRC = ("'self'",), CSP_SCRIPT_SRC =
("'self'", "'unsafe-inline'") (adjust as needed for your specific app,
but be cautious with unsafe-inline).

8. End-of-Course Projects (5 Ideas)


These projects are designed to challenge your understanding and integrate various concepts
learned throughout the course. Each project should include both a Django backend (with DRF
APIs) and a React frontend (with a styling framework).

1. Mini E-commerce Store:


o Features: Product catalog with images, product details, user authentication
(register/login), shopping cart, basic order placement (simulated payment).
o Completion: Users can browse products, add them to a cart, manage
quantities, register/login, and proceed through a simulated checkout.
2. Real-time Chat Application:
o Features: User authentication, one-on-one chat, public chat rooms, real-time
message display (using Django Channels/WebSockets), message history.
o Completion: Users can register/login, join chat rooms, send and receive
messages in real-time, and view past conversations.
3. Simple Learning Management System (LMS):
o Features: User roles (Student, Instructor), Course creation/listing, Lesson
content (text/video links), Student enrollment in courses, basic lesson
completion tracking.
o Completion: Instructors can create courses and lessons. Students can register,
enroll in courses, view lessons, and mark lessons as complete.
4. Basic Inventory Management System:
o Features: Item management (add/edit/delete items with name, quantity,
description), stock adjustments (record incoming/outgoing), view current stock
levels, user authentication for management.
o Completion: Authenticated users can manage inventory items, record stock
movements, and view current stock status.
5. Personalized Dashboard / Portfolio Site:
o Features: User authentication, customizable dashboard sections (e.g., "My
Tasks", "My Notes", "My Projects"), CRUD operations for content within each
section. Can be adapted for a developer's portfolio where they manage
projects, blog posts, etc.
o Completion: Users can log in, access a personalized dashboard, and
create/manage content within predefined sections.

This revised course provides a clear and focused path for building full-stack web applications
with React and Django. Remember that consistent practice through coding is key to mastering
these technologies. Good luck on your full-stack development journey!

You might also like