0% found this document useful (0 votes)
56 views47 pages

Django React 1

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)
56 views47 pages

Django React 1

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/ 47

This comprehensive course will guide you through building various web applications using

React for the frontend (with high-level styling frameworks) and Django for the backend. Each
module includes assignments to solidify your understanding, with answers provided at the end
of the document. Finally, you'll tackle 10 diverse end-of-course projects to showcase your
full-stack development skills.

Complete Courses on Building Websites with React and


Django
Course Overview

This course is designed to take you from a beginner to a confident full-stack developer using
React for dynamic user interfaces and Django for robust backend logic and data management.
We'll cover essential concepts, modern tools, and practical application development for
various web systems, including e-marketing, chat applications, learning management systems,
and inventory management.

Prerequisites:

 Basic understanding of HTML, CSS, and JavaScript.


 Familiarity with Python fundamentals.
 Familiarity with command-line interface (CLI).

Tools and Technologies:

 Frontend: React, [Link], npm/yarn, React Router, Redux (for state management),
high-level styling frameworks (Tailwind CSS, Material UI, Chakra UI), Axios (for
API calls).
 Backend: Django, Django REST Framework, PostgreSQL (or other relational
database), Django Channels (for WebSockets), Djoser (for authentication).
 Version Control: Git, GitHub.
 Development Environment: VS Code (recommended).

Module 1: Foundations of Web Development & Python Refresher

Learning Objectives:

 Understand the fundamental concepts of web development (client-server architecture,


HTTP/HTTPS).
 Review Python basics necessary for Django.
 Set up your development environment.
 Introduction to Git and GitHub for version control.

Topics:
1. Web Development Fundamentals:
o How the web works (HTTP requests/responses).
o Frontend vs. Backend.
o Client-Server architecture.
o APIs (RESTful principles).
2. Python Refresher:
o Variables, data types, operators.
o Control flow (if/else, loops).
o Functions.
o Object-Oriented Programming (OOP) concepts.
o Virtual environments (venv).
3. Introduction to Git and GitHub:
o What is version control?
o Basic Git commands: git init, git add, git commit, git status, git
log.
o Working with remote repositories: git clone, git push, git pull.

Assignments:

 Assignment 1.1: Python Refresher Quiz


o Create a Python script that takes a user's name and age as input, then prints a
personalized greeting and calculates the year they will turn 100.
 Assignment 1.2: Git Practice
o Create a new GitHub repository.
o Clone it to your local machine.
o Create a new file, add some text, commit the changes, and push them to
GitHub.
o Make another change, commit, and push.

Answers (at the end of the document)

Module 2: Django Backend Development - Core Concepts

Learning Objectives:

 Understand the Django MVT (Model-View-Template) architecture.


 Set up a Django project and application.
 Define data models and perform database migrations.
 Create basic views, URLs, and templates.
 Work with the Django Admin interface.

Topics:

1. Django Project Setup:


o django-admin startproject.
o python [Link] startapp.
o [Link] configuration (INSTALLED_APPS, DATABASES).
2. Django Models:
o Defining database schemas using Django ORM.
o Field types (CharField, IntegerField, DateTimeField, ForeignKey,
ManyToManyField).
o makemigrations and migrate.
o Interacting with the database through the Django Shell.
3. Django Views and URLs:
o Function-based views.
o Class-based views (introduction).
o URL routing ([Link]).
o Passing data from views to templates.
4. Django Templates:
o Template syntax (variables, tags, filters).
o Template inheritance.
o Rendering static files.
5. Django Admin:
o Registering models with the admin interface.
o Creating a superuser.
o Basic data management through the admin panel.

Assignments:

 Assignment 2.1: Blog Application Backend


o Create a Django project named BlogSite and an app named blog.
o Define a Post model with fields for title (CharField), content (TextField),
author (ForeignKey to User model), and published_date (DateTimeField).
o Make and apply migrations.
o Register the Post model in the Django Admin.
o Create a superuser and add a few sample posts through the admin.
o Create a view that fetches all posts and renders them in a simple HTML
template. Define a URL for this view.
 Assignment 2.2: User Profile Extension
o Extend the Django User model (e.g., by creating a Profile model with a
OneToOneField to User) to add a bio (TextField) and profile_picture
(ImageField).
o Ensure the Profile model can be managed in the Django Admin.

Answers (at the end of the document)

Module 3: Django REST Framework for API Development

Learning Objectives:

 Understand the principles of RESTful APIs.


 Build powerful APIs using Django REST Framework (DRF).
 Implement serialization, views, and routing for APIs.
 Handle authentication and permissions for API endpoints.

Topics:
1. Introduction to RESTful APIs:
o HTTP methods (GET, POST, PUT, DELETE).
o Statelessness.
o Resource-based URLs.
2. Django REST Framework Setup:
o Installation and configuration.
o Serializers: converting Django models to JSON and vice-versa.
o ModelSerializers.
3. DRF Views:
o APIView.
o Generic APIView and mixins.
o ViewSets and Routers.
4. Authentication and Permissions:
o Token-based authentication.
o Session authentication.
o Permission classes (IsAuthenticated, IsAdminUser,
IsAuthenticatedOrReadOnly).
o Using Djoser for user registration and authentication endpoints.

Assignments:

 Assignment 3.1: Blog API Development


o Install Django REST Framework in your BlogSite project.
o Create a serializer for the Post model.
o Create a PostListCreateAPIView (or ModelViewSet) to handle listing and
creating posts via API.
o Create a PostDetailAPIView (or part of ModelViewSet) to handle retrieving,
updating, and deleting individual posts.
o Configure URLs for these API endpoints.
o Test your API using a tool like Postman or Insomnia.
 Assignment 3.2: User Authentication API
o Integrate Djoser into your project for user registration and login.
o Ensure that only authenticated users can create, update, or delete Post objects.
o Test user registration and token-based authentication.

Answers (at the end of the document)

Module 4: React Frontend Development - Basics

Learning Objectives:

 Understand React's component-based architecture.


 Set up a React project.
 Work with JSX, components, props, and state.
 Handle events and forms in React.
 Manage routing with React Router.

Topics:
1. Introduction to React:
o Why React? (Declarative, Component-Based, Learn Once Write Anywhere).
o Virtual DOM.
o create-react-app.
2. JSX (JavaScript XML):
o Writing HTML-like code in JavaScript.
o Embedding expressions.
3. React Components:
o Functional components vs. Class components (focus on functional).
o Props: passing data down the component tree.
o State and useState hook: managing component-specific data.
o Lifecycle methods and useEffect hook.
4. Event Handling:
o Handling user interactions (clicks, input changes).
5. Forms in React:
o Controlled components.
o Handling form submissions.
6. React Router:
o Setting up client-side routing.
o BrowserRouter, Routes, Route, Link, useNavigate.

Assignments:

 Assignment 4.1: Simple React Counter


o Create a new React project.
o Build a functional component that displays a number and has two buttons:
"Increment" and "Decrement".
o Clicking the buttons should increase/decrease the number.
 Assignment 4.2: Basic To-Do List
o Create a React component that displays a list of to-do items.
o Allow users to add new items to the list via an input field and a button.
o Allow users to mark items as complete (e.g., by toggling a strikethrough).
 Assignment 4.3: Navigation Practice
o Add React Router to your project.
o Create two simple pages (e.g., "Home" and "About").
o Implement navigation links between these pages.

Answers (at the end of the document)

Module 5: React Frontend - Advanced Concepts & Styling

Learning Objectives:

 Manage global state with Redux Toolkit.


 Fetch data from Django APIs using Axios.
 Apply high-level styling frameworks (Tailwind CSS, Material UI, Chakra UI).
 Understand responsive design principles.
Topics:

1. State Management with Redux Toolkit:


o Why state management?
o Core Redux concepts (store, reducers, actions, selectors).
o Simplifying Redux with Redux Toolkit (createSlice, configureStore).
o Integrating Redux with React (react-redux hooks).
2. Fetching Data with Axios:
o Making GET, POST, PUT, DELETE requests to your Django API.
o Handling asynchronous operations (async/await).
o Error handling.
o CORS configuration in Django.
3. High-Level Styling Frameworks:
o Tailwind CSS:
 Utility-first CSS framework.
 Installation and setup.
 Applying utility classes.
 Responsive design with Tailwind.
o Material UI (MUI):
 Google's Material Design implementation for React.
 Installation and usage of components.
 Customizing themes.
o Chakra UI:
 A simple, modular, and accessible component library.
 Installation and usage.
 Styling props.
o Choose one framework to focus on for in-depth practice.
4. Responsive Design Principles:
o Media queries (brief overview if not covered by framework).
o Fluid layouts.

Assignments:

 Assignment 5.1: Blog Frontend with API Integration


o Connect your React frontend to the Django Blog API.
o Display a list of posts fetched from the API.
o Implement a form to create new posts (requires user authentication setup).
o Implement a simple view for a single post.
o Add functionality to delete posts (requires user authentication).
 Assignment 5.2: State Management with Redux Toolkit
o Refactor the blog application to use Redux Toolkit for managing the list of
posts and potentially user authentication state.
o Implement actions to fetch posts, add posts, and delete posts.
o Connect your components to the Redux store.
 Assignment 5.3: Styling the Blog
o Apply either Tailwind CSS, Material UI, or Chakra UI to style your blog
application.
o Ensure the layout is responsive and looks good on different screen sizes.

Answers (at the end of the document)


Module 6: Building an E-Marketing Website (E-commerce focused)

Learning Objectives:

 Develop an e-commerce platform with product listings, cart, and checkout.


 Implement user authentication (login, registration).
 Handle image uploads for products.
 Manage orders and user profiles.

Key Features for E-Marketing/E-commerce:

 Product Management: Add, edit, delete products with details (name, description,
price, stock, images).
 User Authentication: Registration, login, logout, password reset.
 Shopping Cart: Add/remove items, update quantities.
 Checkout Process: Order summary, payment integration (mock or simplified),
shipping details.
 Order History: Users can view their past orders.
 Search and Filtering: Search products by name, category, price.
 Admin Dashboard: For managing products, users, and orders.

Assignments:

 Assignment 6.1: Product Catalog Backend


o Create Django models for Product (name, description, price, stock, image),
Category.
o Set up DRF serializers and views for products and categories (list, detail,
create, update, delete).
o Implement image uploads for products.
 Assignment 6.2: Frontend Product Display
o Create React components to display a list of products with images, names, and
prices.
o Implement a search bar and category filters.
o Create a detailed product page.
 Assignment 6.3: Basic Shopping Cart
o Implement a client-side shopping cart using React's local state or Redux.
o Allow users to add products to the cart from the product list and detail pages.
o Display cart items and total.

Answers (at the end of the document)

Module 7: Developing a Chat Application

Learning Objectives:

 Understand real-time communication with WebSockets.


 Implement Django Channels for WebSocket functionality.
 Build a real-time chat interface with React.

Key Features for Chat App:

 Real-time Messaging: Instant message sending and receiving.


 User Presence: Show online/offline status (optional, advanced).
 Group Chats: (Optional, advanced)
 Message History: Display past messages.
 Typing Indicators: (Optional, advanced)

Assignments:

 Assignment 7.1: Chat Backend with Django Channels


o Install Django Channels.
o Configure your Django project for Channels (ASGI application).
o Create a simple chat model (Message with sender, content, timestamp,
room/conversation).
o Implement a WebSocket consumer that handles connecting, disconnecting, and
receiving/sending messages for a specific chat room.
o Set up routing for WebSocket connections.
 Assignment 7.2: React Real-time Chat Frontend
o Create a React component for a chat interface.
o Establish a WebSocket connection to your Django Channels backend.
o Display incoming messages in real-time.
o Implement an input field to send messages.
o Ensure messages are displayed in chronological order.

Answers (at the end of the document)

Module 8: Building a Learning Management System (LMS)

Learning Objectives:

 Design and implement a system for course creation and enrollment.


 Manage users (students, instructors).
 Develop features for quizzes and assignments.

Key Features for LMS:

 Course Management: Create, edit, publish courses with lessons and topics.
 User Roles: Students and Instructors.
 Enrollment: Students can enroll in courses.
 Lesson Viewing: Display course content (text, video links).
 Quizzes/Assignments: Create, take, and grade quizzes/assignments.
 Progress Tracking: Students can see their progress in courses.
 Instructor Dashboard: Manage their courses, view student progress.
Assignments:

 Assignment 8.1: LMS Backend Models


o Define Django models for Course (title, description, instructor - ForeignKey),
Lesson (title, content, course - ForeignKey), Quiz (title, course - ForeignKey),
Question (text, quiz - ForeignKey), Option (text, is_correct, question -
ForeignKey), Enrollment (student - ForeignKey, course - ForeignKey,
date_enrolled).
o Set up DRF serializers and views for these models.
 Assignment 8.2: Course Listing and Enrollment Frontend
o Create a React component to list available courses.
o Implement functionality for authenticated students to enroll in a course.
o Create a "My Courses" page where enrolled students can see their courses.
 Assignment 8.3: Basic Quiz Taking
o Implement a React component to display a quiz.
o Allow students to select answers and submit the quiz.
o (Optional, advanced) Display immediate feedback or a score after submission.

Answers (at the end of the document)

Module 9: Developing an Inventory Management System

Learning Objectives:

 Create a system for tracking product inventory.


 Manage stock levels, suppliers, and orders.
 Generate reports for inventory analysis.

Key Features for Inventory Management:

 Item Management: Add, edit, delete inventory items (name, SKU, quantity, price,
location).
 Stock Tracking: Real-time updates of stock levels.
 Supplier Management: Store supplier information.
 Order Management (Purchase/Sales): Create and track purchase orders (incoming
stock) and sales orders (outgoing stock).
 Inventory Alerts: Low stock notifications.
 Reporting: Generate reports on current stock, sales, and purchase history.
 Multi-location Support: (Optional, advanced) Manage inventory across multiple
warehouses.

Assignments:

 Assignment 9.1: Inventory Backend Models & API


o Define Django models for Item (name, SKU, quantity, price, description,
location), Supplier (name, contact_info), PurchaseOrder (supplier, date,
items - ManyToMany with quantity), SaleOrder (customer, date, items -
ManyToMany with quantity).
o Set up DRF serializers and views for these models.
o Implement logic to update Item quantities when PurchaseOrder or
SaleOrder items are created/updated.
 Assignment 9.2: Item Listing and Stock Management Frontend
o Create a React component to display a list of inventory items with their
quantities.
o Implement functionality to update an item's quantity manually (e.g., for
adjustments).
o Create a form to add new inventory items.
 Assignment 9.3: Simple Purchase Order Entry
o Create a React form to create a new PurchaseOrder.
o Allow users to select a supplier and add multiple items with quantities to the
order.
o Upon submission, ensure the backend updates the inventory correctly.

Answers (at the end of the document)

Module 10: Deployment and Best Practices

Learning Objectives:

 Prepare your Django and React applications for production.


 Understand common deployment strategies.
 Review best practices for security, performance, and code organization.

Topics:

1. Deployment Strategies:
o Django Deployment:
 Gunicorn/uWSGI as WSGI server.
 Nginx as a reverse proxy.
 Collecting static files.
 Environment variables.
 Brief overview of cloud platforms (Heroku, AWS, DigitalOcean).
o React Deployment:
 Building for production (npm run build).
 Serving static files.
 Deployment to Netlify, Vercel, or integrating with Django's Nginx
setup.
2. Security Best Practices:
o Django security features (CSRF, XSS protection).
o Securing API endpoints.
o Handling sensitive data.
o CORS configuration.
3. Performance Optimization:
o Database indexing.
o Caching (Django caching, React memoization).
o Lazy loading React components.
4. Code Organization and Maintainability:
o Modular Django apps.
o Reusable React components.
o Consistent naming conventions.
o Testing strategies (unit, integration - brief overview).

Assignments:

 Assignment 10.1: Prepare for Production


o In your BlogSite project, adjust Django [Link] for production (e.g.,
DEBUG = False, configure ALLOWED_HOSTS).
o Run collectstatic.
o Build your React frontend (npm run build).
 Assignment 10.2: Mini Deployment Plan
o Outline a simple deployment plan for your BlogSite application, including:
 Chosen cloud provider (e.g., Heroku).
 Steps for deploying Django.
 Steps for deploying React.
 How you would connect them.

Answers (at the end of the document)

End of Course Projects (10 with Completions)

These projects are designed to integrate the knowledge gained throughout the course. For
each project, focus on building a minimal viable product (MVP) with core functionalities,
then consider adding optional advanced features.

General Completion Requirements for Projects:

 Django Backend:
o Well-defined models with appropriate relationships.
o DRF APIs for all necessary CRUD (Create, Read, Update, Delete) operations.
o User authentication (registration, login, logout) using Djoser or similar.
o Proper URL routing.
o Sensible database migrations.
 React Frontend:
o Component-based architecture.
o State management (Redux Toolkit recommended for complex state).
o API integration with Axios.
o Client-side routing with React Router.
o High-level styling framework applied consistently.
o Responsive design.
o Clear and intuitive user interface.
 Version Control: Project hosted on GitHub with clear commit history.
 Documentation: A [Link] file explaining how to set up and run the project, and
any key architectural decisions.
Project 1: Advanced Blog Platform

 Core Features:
o User authentication (register, login, logout, password reset).
o Create, read, update, delete blog posts.
o Add comments to posts.
o Like/dislike posts (basic).
o User profiles displaying their posts and comments.
o Search functionality for posts.
 Advanced Features (Optional):
o Rich text editor for post content.
o Tags/categories for posts.
o Draft posts functionality.
o Image uploads for posts.
o Admin dashboard for managing all content.

Project 2: E-commerce Store with Payment Gateway Integration (Mock)

 Core Features:
o Product catalog with categories and search.
o Product detail pages with images, descriptions, and "Add to Cart" button.
o Shopping cart (add, remove, update quantities).
o User registration and login.
o Checkout process with mock payment.
o Order history for users.
o Basic admin panel to manage products and view orders.
 Advanced Features (Optional):
o Real payment gateway integration (e.g., Stripe, PayPal - for learning purposes,
not production).
o User reviews and ratings for products.
o Wishlist functionality.
o Shipping address management.
o Inventory management integration (low stock alerts).

Project 3: Real-time Collaborative Whiteboard/Drawing App

 Core Features:
o User authentication.
o Create and join "rooms" or "boards."
o Real-time drawing and erasing functionality (lines, shapes) synchronized
across connected users in the same room.
o Use Django Channels for WebSocket communication.
 Advanced Features (Optional):
o Different colors and brush sizes.
o Text tool.
o Saving and loading drawings.
o Undo/redo functionality.
o User cursors visible to others.
Project 4: Online Learning Platform with Course Progress

 Core Features:
o Two user roles: Student and Instructor.
o Instructors can create courses, add lessons (text, video links), and
assignments/quizzes.
o Students can enroll in courses, view lessons, and submit assignments/take
quizzes.
o Track student progress within courses.
o Instructor dashboard to view enrolled students and their progress.
 Advanced Features (Optional):
o Course discussion forums.
o Certificates upon course completion.
o Grading system for assignments.
o Live Q&A sessions (using chat functionality).
o Rating/review system for courses.

Project 5: Inventory Management System with Barcode/QR Code Support

 Core Features:
o Manage inventory items (name, SKU, quantity, location, description).
o Record incoming (purchase orders) and outgoing (sales orders) stock.
o Update stock levels automatically based on orders.
o Generate low stock alerts.
o Supplier management.
o Basic reporting (current stock levels, recent movements).
 Advanced Features (Optional):
o Integration with a barcode/QR code scanner (simulated or real).
o Multi-warehouse/location management.
o Demand forecasting (simple).
o Audit trails for all inventory changes.
o User roles with different permissions.

Project 6: Job Board Platform

 Core Features:
o User roles: Job Seeker and Employer.
o Employers can post job listings (title, description, requirements, location,
salary range).
o Job seekers can browse, search, and filter job listings.
o Job seekers can apply to jobs (simple form with resume upload - mock).
o Employer dashboard to manage their job postings and view applications.
 Advanced Features (Optional):
o User profiles for job seekers (skills, experience).
o Employer profiles.
o Notifications for new relevant jobs.
o Application tracking system for employers.
o Integrated messaging between job seekers and employers.

Project 7: Personal Portfolio & Project Showcase


 Core Features:
o An "About Me" section.
o A "Projects" section to showcase past work with descriptions, technologies
used, and links to live demos/GitHub repos.
o A "Skills" section.
o A "Contact" form that sends emails (using Django's email backend or a third-
party service).
o Admin panel to update portfolio content.
 Advanced Features (Optional):
o Blog section.
o Dynamic project filtering by technology.
o Downloadable resume.
o Testimonials section.

Project 8: Simple Social Media Feed

 Core Features:
o User authentication.
o Users can create posts (text, optional image upload).
o Users can like/unlike posts.
o Users can comment on posts.
o A main feed displaying posts from all users.
o User profiles displaying their posts.
 Advanced Features (Optional):
o Follow/unfollow users.
o Notifications (e.g., when someone likes/comments on your post).
o Hashtags and trending topics.
o Real-time updates for likes/comments (using WebSockets).

Project 9: Event Management and Ticketing System

 Core Features:
o User authentication.
o Create events (name, date, time, location, description, ticket price, capacity).
o Browse and search for events.
o Register for events/purchase tickets (mock payment).
o View registered/purchased events.
o Admin dashboard to manage events and view attendees.
 Advanced Features (Optional):
o QR code generation for tickets.
o Event categories.
o Attendee check-in functionality.
o Email notifications for event registration.

Project 10: Recipe Sharing Platform

 Core Features:
o User authentication.
o Users can create and share recipes (name, ingredients, instructions, categories,
cooking time).
o Browse and search for recipes.
o Rate and review recipes.
o User profiles displaying their shared recipes.
 Advanced Features (Optional):
o Save recipes to a "favorites" list.
o Ingredient search (find recipes based on ingredients you have).
o Meal planning functionality.
o Nutritional information integration.
o Video recipes.

Assignments Answers

Module 1: Foundations of Web Development & Python Refresher

Assignment 1.1: Python Refresher Quiz - Answer

Python
name = input("Enter your name: ")
age_str = input("Enter your age: ")

try:
age = int(age_str)
current_year = 2025 # Assuming current year for calculation
year_turns_100 = current_year + (100 - age)
print(f"Hello, {name}! You are {age} years old.")
print(f"You will turn 100 in the year {year_turns_100}.")
except ValueError:
print("Invalid age entered. Please enter a number.")

Assignment 1.2: Git Practice - Completion

 Step 1: Create a new GitHub repository.


o Go to [Link] and create a new repository (e.g., my-first-git-repo). Do
not initialize with a README for this exercise.
 Step 2: Clone it to your local machine.
o Open your terminal/command prompt.
o Navigate to your desired directory.
o Run: git clone <YOUR_REPOSITORY_URL> (e.g., git clone
[Link]
o cd my-first-git-repo
 Step 3: Create a new file, add some text, commit the changes, and push them to
GitHub.
o echo "Hello, Git!" > [Link]
o git add [Link]
o git commit -m "Initial commit: Added [Link]"
o git push origin main (or master, depending on your default branch name)
 Step 4: Make another change, commit, and push.
o echo "This is a second line." >> [Link]
o git add [Link]
o git commit -m "Added a second line to [Link]"
o git push origin main

Module 2: Django Backend Development - Core Concepts

Assignment 2.1: Blog Application Backend - Completion

1. Create Django Project and App:

Bash

django-admin startproject BlogSite


cd BlogSite
python [Link] startapp blog

2. [Link] (in BlogSite/BlogSite/[Link]): Add blog to


INSTALLED_APPS:

Python

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'blog', # Add this line
]

3. Post Model (in BlogSite/blog/[Link]):

Python

from [Link] import models


from [Link] import User

class Post([Link]):
title = [Link](max_length=200)
content = [Link]()
author = [Link](User, on_delete=[Link])
published_date = [Link](auto_now_add=True)

def __str__(self):
return [Link]

4. Make and Apply Migrations:

Bash

python [Link] makemigrations


python [Link] migrate
5. Register Post in Django Admin (BlogSite/blog/[Link]):

Python

from [Link] import admin


from .models import Post

[Link](Post)

6. Create Superuser and Add Sample Posts:

Bash

python [Link] createsuperuser


# Follow prompts to create username, email, password

Then run python [Link] runserver, navigate to


[Link] log in, and add some Post objects.

7. Create View (BlogSite/blog/[Link]):

Python

from [Link] import render


from .models import Post

def post_list(request):
posts = [Link]().order_by('-published_date')
context = {'posts': posts}
return render(request, 'blog/post_list.html', context)

8. Create URLs (BlogSite/blog/[Link]):

Python

from [Link] import path


from . import views

urlpatterns = [
path('posts/', views.post_list, name='post_list'),
]

9. Include App URLs in Project URLs (BlogSite/BlogSite/[Link]):

Python

from [Link] import admin


from [Link] import path, include

urlpatterns = [
path('admin/', [Link]),
path('blog/', include('[Link]')), # Include your app's URLs
]
10. Create Template (BlogSite/blog/templates/blog/post_list.html):

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Blog Posts</title>
</head>
<body>
<h1>All Blog Posts</h1>
{% if posts %}
<ul>
{% for post in posts %}
<li>
<h2>{{ [Link] }}</h2>
<p>By {{ [Link] }} on {{
post.published_date }}</p>
<p>{{ [Link]|truncatewords:50 }}</p>
</li>
{% endfor %}
</ul>
{% else %}
<p>No blog posts found.</p>
{% endif %}
</body>
</html>

Now, run python [Link] runserver and navigate to


[Link] to see your posts.

Assignment 2.2: User Profile Extension - Completion

1. Profile Model (in BlogSite/blog/[Link] - assuming you want it in the blog


app for simplicity, or create a new users app):

Python

from [Link] import models


from [Link] import User

class Post([Link]):
# ... (existing Post model) ...

class Profile([Link]):
user = [Link](User, on_delete=[Link])
bio = [Link](blank=True, null=True)
profile_picture = [Link](upload_to='profile_pics/',
blank=True, null=True)

def __str__(self):
return [Link]

2. Make and Apply Migrations:


Bash

python [Link] makemigrations


python [Link] migrate

3. Register Profile in Django Admin (BlogSite/blog/[Link]):

Python

from [Link] import admin


from .models import Post, Profile

[Link](Post)
[Link](Profile)

Now, in the Django Admin, you'll see a "Profiles" section where you can create and
manage user profiles. Each User object will have a link to create/edit their associated
Profile.

Module 3: Django REST Framework for API Development

Assignment 3.1: Blog API Development - Completion

1. Install DRF:

Bash

pip install djangorestframework

2. Add rest_framework to INSTALLED_APPS (in BlogSite/BlogSite/[Link]):

Python

INSTALLED_APPS = [
# ... existing apps ...
'rest_framework', # Add this
'blog',
]

3. Create Serializer (BlogSite/blog/[Link]):

Python

from rest_framework import serializers


from .models import Post

class PostSerializer([Link]):
author = [Link](source='[Link]') #
Display author's username

class Meta:
model = Post
fields = ['id', 'title', 'content', 'author',
'published_date']
read_only_fields = ['author', 'published_date'] # Prevent
direct modification of these fields

4. Create DRF Views (BlogSite/blog/[Link] - add to existing file or create


api_views.py):

Python

from rest_framework import generics


from rest_framework.permissions import IsAuthenticatedOrReadOnly
from .models import Post
from .serializers import PostSerializer

class PostListCreateAPIView([Link]):
queryset = [Link]().order_by('-published_date')
serializer_class = PostSerializer
permission_classes = [IsAuthenticatedOrReadOnly] # Allow read for
anyone, create for authenticated

def perform_create(self, serializer):


[Link](author=[Link]) # Assign the
logged-in user as author

class PostDetailAPIView([Link]):
queryset = [Link]()
serializer_class = PostSerializer
permission_classes = [IsAuthenticatedOrReadOnly] # Allow read for
anyone, update/delete for authenticated

# Optional: Custom permission to allow only author to edit/delete


# from rest_framework import permissions
# class IsAuthorOrReadOnly([Link]):
# def has_object_permission(self, request, view, obj):
# if [Link] in permissions.SAFE_METHODS:
# return True
# return [Link] == [Link]
# permission_classes = [IsAuthorOrReadOnly]

5. Configure API URLs (BlogSite/blog/[Link] - add to existing file):

Python

from [Link] import path


from . import views # For traditional views
from .views import PostListCreateAPIView, PostDetailAPIView # For DRF
views

urlpatterns = [
path('posts/', views.post_list, name='post_list'), # Keep
existing for template view
path('api/posts/', PostListCreateAPIView.as_view(),
name='api_post_list_create'),
path('api/posts/<int:pk>/', PostDetailAPIView.as_view(),
name='api_post_detail'),
]
6. Test your API:
o Run python [Link] runserver.
o Open Postman or Insomnia.
o GET [Link] Should return a list of
your posts.
o POST [Link]
 Set Content-Type: application/json.
 Body: {"title": "My New API Post", "content": "This is
content from the API."}
 If not logged in, it should give a permission error.
 To test authentication, you'll need a user token (see Assignment 3.2).
Once authenticated, you can send the Authorization: Token
<your_token> header.

Assignment 3.2: User Authentication API - Completion

1. Install Djoser:

Bash

pip install djoser

2. Add djoser and rest_framework.authtoken to INSTALLED_APPS (in


BlogSite/BlogSite/[Link]):

Python

INSTALLED_APPS = [
# ... existing apps ...
'rest_framework',
'rest_framework.authtoken', # For token authentication
'djoser', # For user management endpoints
'blog',
]

# Add DRF authentication settings


REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.[Link]',
'rest_framework.[Link]', #
Optional, useful for browsable API
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.[Link]', #
Default for all APIs
)
}

3. Include Djoser URLs (in BlogSite/BlogSite/[Link]):

Python

from [Link] import admin


from [Link] import path, include
urlpatterns = [
path('admin/', [Link]),
path('blog/', include('[Link]')),
path('auth/', include('[Link]')), # Djoser user management
path('auth/', include('[Link]')), # Djoser token
authentication
]

4. Make Migrations for authtoken:

Bash

python [Link] migrate

5. Test User Registration and Token Authentication:


o Run python [Link] runserver.
o POST [Link] (Register User):
 Body (raw JSON): {"username": "testuser", "password":
"securepassword123", "email": "test@[Link]"}
 You should get a 201 Created response.
o POST [Link] (Get Token):
 Body (raw JSON): {"username": "testuser", "password":
"securepassword123"}
 You should get a 200 OK response with a token field. Copy this token.
o Test Protected API (Create Post as Authenticated User):
 POST [Link]
 Headers: Content-Type: application/json,
Authorization: Token <THE_TOKEN_YOU_COPIED>
 Body (raw JSON): {"title": "My Authenticated Post",
"content": "This post was created by an
authenticated user."}
 This should now succeed with a 201 Created response.

Module 4: React Frontend Development - Basics

Assignment 4.1: Simple React Counter - Completion

1. Create React App:

Bash

npx create-react-app my-counter-app


cd my-counter-app

2. src/[Link]:

JavaScript

import React, { useState } from 'react';


import './[Link]'; // You can keep or remove this, depending on your
styling

function App() {
const [count, setCount] = useState(0);

const increment = () => {


setCount(count + 1);
};

const decrement = () => {


setCount(count - 1);
};

return (
<div className="App">
<header className="App-header">
<h1>Simple Counter</h1>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</header>
</div>
);
}

export default App;

3. Run the app:

Bash

npm start

(Opens in browser at [Link]

Assignment 4.2: Basic To-Do List - Completion

1. src/[Link]:

JavaScript

import React, { useState } from 'react';

function TodoList() {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState('');

const addTodo = () => {


if ([Link]() !== '') {
setTodos([...todos, { id: [Link](), text: newTodo, completed:
false }]);
setNewTodo('');
}
};

const toggleComplete = (id) => {


setTodos([Link](todo =>
[Link] === id ? { ...todo, completed: ![Link] } : todo
));
};

return (
<div>
<h1>My To-Do List</h1>
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo([Link])}
placeholder="Add a new todo..."
/>
<button onClick={addTodo}>Add Todo</button>
<ul>
{[Link](todo => (
<li key={[Link]} style={{ textDecoration: [Link] ?
'line-through' : 'none' }}>
{[Link]}
<button onClick={() => toggleComplete([Link])} style={{
marginLeft: '10px' }}>
{[Link] ? 'Undo' : 'Complete'}
</button>
</li>
))}
</ul>
</div>
);
}

export default TodoList;

2. src/[Link] (to render TodoList):

JavaScript

import React from 'react';


import TodoList from './TodoList';
import './[Link]';

function App() {
return (
<div className="App">
<header className="App-header">
<TodoList />
</header>
</div>
);
}

export default App;

3. Run the app: npm start

Assignment 4.3: Navigation Practice - Completion

1. Install React Router DOM:


Bash

npm install react-router-dom

2. src/[Link]:

JavaScript

import React from 'react';


import { BrowserRouter as Router, Routes, Route, Link } from 'react-
router-dom';
import './[Link]';

const Home = () => <h2>Home Page</h2>;


const About = () => <h2>About Us Page</h2>;

function App() {
return (
<Router>
<div className="App">
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>

<header className="App-header">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</header>
</div>
</Router>
);
}

export default App;

3. Run the app: npm start

Module 5: React Frontend - Advanced Concepts & Styling

Assignment 5.1: Blog Frontend with API Integration - Completion (Conceptual Outline)

 This assignment involves connecting your React frontend to the Django Blog API
from Module 3.

1. Install Axios: npm install axios


2. src/components/[Link]:
o Use useState for posts data and useEffect to fetch data on component
mount.
o Inside useEffect, make an
[Link]('[Link] call.
o Map through posts to display them.
3. src/components/[Link]:
o A form with input fields for title and content.
o On submit, use [Link]('[Link]
newPostData, { headers: { Authorization: Token ${yourAuthToken}
} }).
o Handle success (e.g., refresh post list) and error.
4. src/components/[Link]:
o Use useParams from React Router to get the id from the URL.
o Fetch individual post data using
[Link]('[Link]
o Display post details.
5. src/[Link]:
o Set up routes for /posts, /posts/new, /posts/:id.
o Implement basic user login/logout (storing token in local storage). This can be
a separate AuthForm component. When a token is available, pass it in headers
for authenticated requests.

Assignment 5.2: State Management with Redux Toolkit - Completion (Conceptual


Outline)

 Refactor Assignment 5.1 to use Redux Toolkit.

1. Install Redux Toolkit and React Redux:

Bash

npm install @reduxjs/toolkit react-redux

2. src/app/[Link]:

JavaScript

import { configureStore } from '@reduxjs/toolkit';


import postsReducer from '../features/posts/postsSlice';
import authReducer from '../features/auth/authSlice'; // If you're
managing auth state in Redux

export const store = configureStore({


reducer: {
posts: postsReducer,
auth: authReducer,
},
});

3. src/features/posts/[Link]:

JavaScript

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';


import axios from 'axios';

export const fetchPosts = createAsyncThunk('posts/fetchPosts', async


() => {
const response = await
[Link]('[Link]
return [Link];
});

export const createPost = createAsyncThunk('posts/createPost', async


(postData, { getState }) => {
const token = getState().[Link]; // Assuming auth token is in
Redux state
const response = await
[Link]('[Link] postData, {
headers: { Authorization: `Token ${token}` }
});
return [Link];
});

export const deletePost = createAsyncThunk('posts/deletePost', async


(postId, { getState }) => {
const token = getState().[Link];
await
[Link](`[Link] {
headers: { Authorization: `Token ${token}` }
});
return postId;
});

const postsSlice = createSlice({


name: 'posts',
initialState: {
items: [],
status: 'idle', // 'idle' | 'loading' | 'succeeded' | 'failed'
error: null,
},
reducers: {},
extraReducers: (builder) => {
builder
.addCase([Link], (state) => {
[Link] = 'loading';
})
.addCase([Link], (state, action) => {
[Link] = 'succeeded';
[Link] = [Link];
})
.addCase([Link], (state, action) => {
[Link] = 'failed';
[Link] = [Link];
})
.addCase([Link], (state, action) => {
[Link]([Link]); // Add new post to the
beginning
})
.addCase([Link], (state, action) => {
[Link] = [Link](post => [Link] !==
[Link]);
});
},
});
export default [Link];

4. src/[Link] (Wrap App with Provider):

JavaScript

import React from 'react';


import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';
import './[Link]';

const root = [Link]([Link]('root'));


[Link](
<[Link]>
<Provider store={store}>
<App />
</Provider>
</[Link]>
);

5. Components using Redux (src/components/[Link]):

JavaScript

import React, { useEffect } from 'react';


import { useSelector, useDispatch } from 'react-redux';
import { fetchPosts, deletePost } from
'../features/posts/postsSlice';
import { Link } from 'react-router-dom';

function PostList() {
const dispatch = useDispatch();
const posts = useSelector((state) => [Link]);
const postStatus = useSelector((state) => [Link]);
const error = useSelector((state) => [Link]);
const authToken = useSelector((state) => [Link]); // Get
token from auth slice

useEffect(() => {
if (postStatus === 'idle') {
dispatch(fetchPosts());
}
}, [postStatus, dispatch]);

const handleDelete = (id) => {


if ([Link]('Are you sure you want to delete this post?'))
{
dispatch(deletePost(id));
}
};

if (postStatus === 'loading') return <div>Loading posts...</div>;


if (postStatus === 'failed') return <div>Error: {error}</div>;

return (
<div>
<h1>Blog Posts</h1>
<Link to="/posts/new">Create New Post</Link>
<ul>
{[Link]((post) => (
<li key={[Link]}>
<Link to={`/posts/${[Link]}`}>
<h2>{[Link]}</h2>
</Link>
<p>By {[Link]} on {new
Date(post.published_date).toLocaleDateString()}</p>
{authToken && ( // Only show delete if user is
authenticated
<button onClick={() =>
handleDelete([Link])}>Delete</button>
)}
</li>
))}
</ul>
</div>
);
}

export default PostList;

(Similar updates for PostForm and PostDetail).

Assignment 5.3: Styling the Blog - Completion (Conceptual Outline for Tailwind CSS)

1. Install Tailwind CSS (in your React project):

Bash

npm install -D tailwindcss postcss autoprefixer


npx tailwindcss init -p

2. Configure [Link]:

JavaScript

/** @type {import('tailwindcss').Config} */


[Link] = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

3. Add Tailwind directives to src/[Link]:

CSS

@tailwind base;
@tailwind components;
@tailwind utilities;
/* Add any custom global styles here */
body {
font-family: sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}

4. Apply Tailwind classes to components:


o src/components/[Link]:

JavaScript

// ... (imports) ...


function PostList() {
// ... (logic) ...
return (
<div className="container mx-auto p-4">
<h1 className="text-4xl font-bold mb-6 text-center
text-gray-800">Blog Posts</h1>
<Link to="/posts/new" className="bg-blue-500
hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mb-6
inline-block">
Create New Post
</Link>
<ul className="grid grid-cols-1 md:grid-cols-2
lg:grid-cols-3 gap-6">
{[Link]((post) => (
<li key={[Link]} className="bg-white
rounded-lg shadow-md p-6">
<Link to={`/posts/${[Link]}`}
className="block">
<h2 className="text-2xl font-
semibold text-gray-900 mb-2 hover:text-blue-600">{{ [Link]
}}</h2>
</Link>
<p className="text-sm text-gray-600 mb-
3">By {[Link]} on {new
Date(post.published_date).toLocaleDateString()}</p>
<p className="text-gray-700">{{
[Link](0, 150) }}...</p>
{authToken && (
<button
onClick={() =>
handleDelete([Link])}
className="mt-4 bg-red-500
hover:bg-red-700 text-white font-bold py-1 px-3 rounded text-
sm"
>
Delete
</button>
)}
</li>
))}
</ul>
</div>
);
}
export default PostList;
o Continue applying classes to other components (forms, detail pages) to achieve
desired styling.

Module 6: Building an E-Marketing Website (E-commerce focused)

Assignment 6.1: Product Catalog Backend - Completion (Conceptual Outline)

1. Django Models (ecommerce_app/[Link]):

Python

from [Link] import models


from [Link] import User

class Category([Link]):
name = [Link](max_length=100, unique=True)
description = [Link](blank=True, null=True)

def __str__(self):
return [Link]

class Product([Link]):
name = [Link](max_length=200)
description = [Link]()
price = [Link](max_digits=10, decimal_places=2)
stock = [Link](default=0)
image = [Link](upload_to='product_images/',
blank=True, null=True)
category = [Link](Category, on_delete=models.SET_NULL,
null=True, blank=True)
created_at = [Link](auto_now_add=True)
updated_at = [Link](auto_now=True)

def __str__(self):
return [Link]

class Order([Link]):
user = [Link](User, on_delete=[Link])
created_at = [Link](auto_now_add=True)
updated_at = [Link](auto_now=True)
is_paid = [Link](default=False)
# Add shipping address fields, total price, etc.

def __str__(self):
return f"Order {[Link]} by {[Link]}"

class OrderItem([Link]):
order = [Link](Order, on_delete=[Link],
related_name='items')
product = [Link](Product, on_delete=models.SET_NULL,
null=True)
quantity = [Link](default=1)
price = [Link](max_digits=10, decimal_places=2) #
Price at time of order

def __str__(self):
return f"{[Link]} of {[Link]}"

2. Serializers (ecommerce_app/[Link]):

Python

from rest_framework import serializers


from .models import Product, Category, Order, OrderItem

class CategorySerializer([Link]):
class Meta:
model = Category
fields = '__all__'

class ProductSerializer([Link]):
category_name = [Link](source='[Link]',
read_only=True)
class Meta:
model = Product
fields = ['id', 'name', 'description', 'price', 'stock',
'image', 'category', 'category_name', 'created_at', 'updated_at']

class OrderItemSerializer([Link]):
product_name = [Link](source='[Link]',
read_only=True)
class Meta:
model = OrderItem
fields = ['id', 'product', 'product_name', 'quantity',
'price']

class OrderSerializer([Link]):
items = OrderItemSerializer(many=True, read_only=True) # Nested
serializer for order items
user_username = [Link](source='[Link]',
read_only=True)
class Meta:
model = Order
fields = ['id', 'user', 'user_username', 'created_at',
'updated_at', 'is_paid', 'items']
read_only_fields = ['user']

3. Views (ecommerce_app/[Link]):

Python

from rest_framework import generics, permissions


from .models import Product, Category, Order, OrderItem
from .serializers import ProductSerializer, CategorySerializer,
OrderSerializer, OrderItemSerializer
from rest_framework.parsers import MultiPartParser, FormParser # For
image uploads

class ProductListCreateAPIView([Link]):
queryset = [Link]().select_related('category') #
Optimize query
serializer_class = ProductSerializer
parser_classes = [MultiPartParser, FormParser] # Required for
image uploads
permission_classes = [[Link]] #
Allow anyone to view, authenticated to create

class ProductDetailAPIView([Link]):
queryset = [Link]()
serializer_class = ProductSerializer
parser_classes = [MultiPartParser, FormParser]
permission_classes = [[Link]]

class CategoryListCreateAPIView([Link]):
queryset = [Link]()
serializer_class = CategorySerializer
permission_classes = [[Link]]

class CategoryDetailAPIView([Link]):
queryset = [Link]()
serializer_class = CategorySerializer
permission_classes = [[Link]]

class OrderListCreateAPIView([Link]):
queryset = [Link]()
serializer_class = OrderSerializer
permission_classes = [[Link]]

def get_queryset(self):
# Users can only see their own orders
return [Link](user=[Link])

def perform_create(self, serializer):


# Logic to create an order and corresponding order items
# This is complex and might require a custom serializer
method or view logic
# For simplicity, this example assumes order items are added
separately or in a custom way.
# You'd typically pass a list of product IDs and quantities,
then create OrderItems.
[Link](user=[Link])

class OrderDetailAPIView([Link]):
queryset = [Link]()
serializer_class = OrderSerializer
permission_classes = [[Link]]

def get_queryset(self):
return [Link](user=[Link])

# Note: OrderItem views might be managed through nested serializers


or custom logic
# rather than separate direct API endpoints for simplicity in a basic
e-commerce app.

4. URLs (ecommerce_app/[Link]):

Python

from [Link] import path


from .views import (
ProductListCreateAPIView, ProductDetailAPIView,
CategoryListCreateAPIView, CategoryDetailAPIView,
OrderListCreateAPIView, OrderDetailAPIView
)

urlpatterns = [
path('products/', ProductListCreateAPIView.as_view(),
name='product-list-create'),
path('products/<int:pk>/', ProductDetailAPIView.as_view(),
name='product-detail'),
path('categories/', CategoryListCreateAPIView.as_view(),
name='category-list-create'),
path('categories/<int:pk>/', CategoryDetailAPIView.as_view(),
name='category-detail'),
path('orders/', OrderListCreateAPIView.as_view(), name='order-
list-create'),
path('orders/<int:pk>/', OrderDetailAPIView.as_view(),
name='order-detail'),
]

5. [Link] (for image uploads and media files):

Python

# At the end of [Link]


MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

And in your project's [Link]:

Python

from [Link] import settings


from [Link] import static

urlpatterns = [
# ... existing paths ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Assignment 6.2: Frontend Product Display - Completion (Conceptual Outline)

1. src/components/[Link]:
o Fetch products from [Link]
o Display product cards (image, name, price) using a grid layout.
o Implement search input and category dropdown filters.
o Each product card links to its detail page.
2. src/components/[Link]:
o Fetch product details based on id from URL.
o Display product image, name, description, price, stock.
o "Add to Cart" button.

Assignment 6.3: Basic Shopping Cart - Completion (Conceptual Outline)

1. src/features/cart/[Link] (Redux Toolkit):

JavaScript

import { createSlice } from '@reduxjs/toolkit';


const cartSlice = createSlice({
name: 'cart',
initialState: {
items: [], // [{ productId, name, price, quantity, image }]
totalQuantity: 0,
totalAmount: 0,
},
reducers: {
addItemToCart: (state, action) => {
const newItem = [Link]; // { productId, name, price,
image }
const existingItem = [Link](item => [Link]
=== [Link]);

if (existingItem) {
[Link]++;
} else {
[Link]({ ...newItem, quantity: 1 });
}
[Link]++;
[Link] += [Link];
},
removeItemFromCart: (state, action) => {
const id = [Link];
const existingItem = [Link](item => [Link]
=== id);
if (existingItem) {
[Link]--;
[Link] -= [Link];
if ([Link] === 1) {
[Link] = [Link](item => [Link] !==
id);
} else {
[Link]--;
}
}
},
// Optionally, a clearCart reducer
},
});

export const { addItemToCart, removeItemFromCart } =


[Link];
export default [Link];

2. src/components/[Link]:
o Import useDispatch and addItemToCart.
o On "Add to Cart" button click, dispatch(addItemToCart({ productId:
[Link], name: [Link], price: [Link], image:
[Link] })).
3. src/components/[Link]:
o Import useSelector to get [Link], [Link],
[Link].
o Display a list of items in the cart with quantity controls and subtotal.
o A "Checkout" button (which will lead to a new module's assignment).
Module 7: Developing a Chat Application

Assignment 7.1: Chat Backend with Django Channels - Completion (Conceptual


Outline)

1. Install Django Channels: pip install channels


2. Configure [Link]:

Python

INSTALLED_APPS = [
# ...
'channels',
'chat_app', # Your new chat app
]

ASGI_APPLICATION = '[Link]' # Or
your_project_name.[Link]

# Optional: Channel layer for production (e.g., Redis)


# CHANNEL_LAYERS = {
# 'default': {
# 'BACKEND': 'channels_redis.[Link]',
# 'CONFIG': {
# "hosts": [('[Link]', 6379)],
# },
# },
# }

3. Create ASGI file (BlogSite/[Link]):

Python

import os
from [Link] import get_asgi_application
from [Link] import ProtocolTypeRouter, URLRouter
from [Link] import AuthMiddlewareStack # For authenticated
websockets
import chat_app.routing # Assuming your chat app is named 'chat_app'

[Link]('DJANGO_SETTINGS_MODULE', '[Link]')

application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
chat_app.routing.websocket_urlpatterns
)
),
})

4. Chat Model (chat_app/[Link]):

Python

from [Link] import models


from [Link] import User
class ChatRoom([Link]):
name = [Link](max_length=255, unique=True)
# Optional: Add members ManyToManyField to User

def __str__(self):
return [Link]

class Message([Link]):
room = [Link](ChatRoom, on_delete=[Link],
related_name='messages')
sender = [Link](User, on_delete=[Link])
content = [Link]()
timestamp = [Link](auto_now_add=True)

class Meta:
ordering = ['timestamp']

def __str__(self):
return f"{[Link]}: {[Link][:50]}"

5. Serializers (chat_app/[Link]):

Python

from rest_framework import serializers


from .models import Message, ChatRoom

class MessageSerializer([Link]):
sender_username = [Link](source='[Link]',
read_only=True)
class Meta:
model = Message
fields = ['id', 'room', 'sender', 'sender_username',
'content', 'timestamp']
read_only_fields = ['sender', 'timestamp']

class ChatRoomSerializer([Link]):
class Meta:
model = ChatRoom
fields = '__all__'

6. Consumers (chat_app/[Link]):

Python

import json
from [Link] import AsyncWebsocketConsumer
from [Link] import User
from .models import Message, ChatRoom
from [Link] import sync_to_async

class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name =
[Link]['url_route']['kwargs']['room_name']
self.room_group_name = f"chat_{self.room_name}"

# Join room group


await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await [Link]()

async def disconnect(self, close_code):


# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)

async def receive(self, text_data):


text_data_json = [Link](text_data)
message_content = text_data_json['message']
sender_id = [Link]['user'].id # Get sender from
authenticated user

if not sender_id:
await [Link](text_data=[Link]({'error':
'Authentication required'}))
return

# Save message to database asynchronously


await self.save_message(sender_id, self.room_name,
message_content)

# Send message to room group


await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message_content,
'sender': [Link]['user'].username,
'timestamp':
str([Link](room__name=self.room_name,
content=message_content, sender_id=sender_id).last().timestamp) #
Quick way to get timestamp
}
)

async def chat_message(self, event):


message = event['message']
sender = event['sender']
timestamp = event['timestamp']

# Send message to WebSocket


await [Link](text_data=[Link]({
'message': message,
'sender': sender,
'timestamp': timestamp
}))

@sync_to_async
def save_message(self, sender_id, room_name, content):
user = [Link](id=sender_id)
room, created =
[Link].get_or_create(name=room_name)
[Link](sender=user, room=room,
content=content)
7. Routing (chat_app/[Link]):

Python

from [Link] import re_path


from . import consumers

websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_name>\w+)/$',
[Link].as_asgi()),
]

8. API Views for ChatRooms and Messages (Optional, for initial fetching of
history): Add ChatRoomListCreateAPIView and MessageListAPIView (filtered by
room) using DRF generics to chat_app/[Link].

Assignment 7.2: React Real-time Chat Frontend - Completion (Conceptual Outline)

1. src/components/[Link]:

JavaScript

import React, { useState, useEffect, useRef } from 'react';


import { useParams } from 'react-router-dom';
import { useSelector } from 'react-redux'; // To get auth token

function ChatRoom() {
const { roomName } = useParams();
const [messages, setMessages] = useState([]);
const [inputMessage, setInputMessage] = useState('');
const ws = useRef(null);
const authToken = useSelector((state) => [Link]); //
Assuming auth token is in Redux state
const messagesEndRef = useRef(null); // For auto-scrolling

useEffect(() => {
// Fetch historical messages from your Django API here if needed
//
[Link](`[Link]
`, { headers: { Authorization: `Token ${authToken}` } })
// .then(res => setMessages([Link]));

// WebSocket connection
[Link] = new
WebSocket(`[Link]
}`); // Pass token as query param

[Link] = () => [Link]("WebSocket connection


opened.");
[Link] = (event) => {
const data = [Link]([Link]);
setMessages((prevMessages) => [...prevMessages, data]);
};
[Link] = () => [Link]("WebSocket connection
closed.");
[Link] = (error) => [Link]("WebSocket error:",
error);
return () => {
[Link]();
};
}, [roomName, authToken]); // Depend on roomName and authToken

useEffect(() => {
[Link]?.scrollIntoView({ behavior: "smooth" });
}, [messages]); // Scroll to bottom when messages change

const sendMessage = () => {


if ([Link]() && [Link] && [Link]
=== [Link]) {
[Link]([Link]({
'message': inputMessage,
}));
setInputMessage('');
}
};

return (
<div className="flex flex-col h-screen max-w-lg mx-auto border
rounded-lg shadow-lg">
<h1 className="text-2xl font-bold p-4 bg-blue-600 text-white
rounded-t-lg">Chat Room: {roomName}</h1>
<div className="flex-grow p-4 overflow-y-auto space-y-2">
{[Link]((msg, index) => (
<div key={index} className={`flex ${[Link] ===
'current_user_username' ? 'justify-end' : 'justify-start'}`}>
<div className={`p-2 rounded-lg ${[Link] ===
'current_user_username' ? 'bg-blue-200' : 'bg-gray-200'}`}>
<p className="font-semibold">{[Link]}</p>
<p>{[Link]}</p>
<span className="text-xs text-gray-500">{{ new
Date([Link]).toLocaleTimeString() }}</span>
</div>
</div>
))}
<div ref={messagesEndRef} />
</div>
<div className="p-4 border-t flex">
<input
type="text"
value={inputMessage}
onChange={(e) => setInputMessage([Link])}
onKeyPress={(e) => [Link] === 'Enter' && sendMessage()}
placeholder="Type your message..."
className="flex-grow border rounded-l-lg p-2 focus:outline-
none focus:ring-2 focus:ring-blue-500"
/>
<button
onClick={sendMessage}
className="bg-blue-500 hover:bg-blue-700 text-white font-
bold py-2 px-4 rounded-r-lg"
>
Send
</button>
</div>
</div>
);
}
export default ChatRoom;

o Note: Passing the authToken via query parameter is a common way for
WebSocket authentication in Channels. In your ChatConsumer, you'd typically
extract and validate this token to associate the WebSocket connection with an
authenticated user. You'd replace 'current_user_username' with the actual
authenticated username.
o Add routing in src/[Link] for /chat/:roomName.

Module 8: Building a Learning Management System (LMS)

Assignment 8.1: LMS Backend Models - Completion (Conceptual Outline)

1. Models (lms_app/[Link]):

Python

from [Link] import models


from [Link] import User

class Course([Link]):
title = [Link](max_length=255)
description = [Link]()
instructor = [Link](User, on_delete=[Link],
related_name='taught_courses')
is_published = [Link](default=False)
created_at = [Link](auto_now_add=True)
updated_at = [Link](auto_now=True)

def __str__(self):
return [Link]

class Lesson([Link]):
course = [Link](Course, on_delete=[Link],
related_name='lessons')
title = [Link](max_length=255)
content = [Link]() # Markdown or simple text
video_url = [Link](blank=True, null=True)
order = [Link](default=0) # For ordering
lessons

class Meta:
ordering = ['order']

def __str__(self):
return f"{[Link]} - {[Link]}"

class Quiz([Link]):
course = [Link](Course, on_delete=[Link],
related_name='quiz')
title = [Link](max_length=255)
description = [Link](blank=True, null=True)

def __str__(self):
return f"Quiz for {[Link]}"
class Question([Link]):
quiz = [Link](Quiz, on_delete=[Link],
related_name='questions')
text = [Link]()
# Add question type (e.g., 'multiple_choice', 'text_answer')

def __str__(self):
return [Link][:50]

class Option([Link]):
question = [Link](Question, on_delete=[Link],
related_name='options')
text = [Link](max_length=255)
is_correct = [Link](default=False)

def __str__(self):
return [Link]

class Enrollment([Link]):
student = [Link](User, on_delete=[Link],
related_name='enrollments')
course = [Link](Course, on_delete=[Link],
related_name='enrollments')
date_enrolled = [Link](auto_now_add=True)
completed_lessons = [Link](Lesson, blank=True)
# Optional: completion_date, progress_percentage

class Meta:
unique_together = ('student', 'course') # A student can
enroll in a course only once

def __str__(self):
return f"{[Link]} enrolled in
{[Link]}"

class Submission([Link]):
enrollment = [Link](Enrollment,
on_delete=[Link])
quiz = [Link](Quiz, on_delete=[Link],
null=True, blank=True)
# For assignments
# assignment = [Link](Assignment,
on_delete=[Link], null=True, blank=True)
submitted_at = [Link](auto_now_add=True)
score = [Link](max_digits=5, decimal_places=2,
null=True, blank=True)
# Add answer field for text answers, or a JSON field for quiz
answers

def __str__(self):
return f"Submission by {[Link]} for
{[Link] if [Link] else 'Assignment'}"

2. Serializers and Views: Create DRF serializers and generics views (ListCreate,
RetrieveUpdateDestroy) for Course, Lesson, Quiz, Question, Option, Enrollment,
Submission. Ensure proper permissions (e.g., only instructors can create/update
courses, students can create enrollments and submissions).
Assignment 8.2: Course Listing and Enrollment Frontend - Completion (Conceptual
Outline)

1. src/components/[Link]:
o Fetch courses from Django API.
o Display each course with title, description, instructor.
o "View Details" button linking to CourseDetail page.
o "Enroll" button for authenticated students.
2. src/components/[Link]:
o Fetch course details.
o Display lessons (list of titles, linking to LessonView).
o Enrollment button/status.
3. src/components/[Link]:
o Fetch Enrollment objects for the authenticated user.
o Display courses the user is enrolled in.
o Links to CourseDetail for enrolled courses.
o (Optional) Display basic progress.

Assignment 8.3: Basic Quiz Taking - Completion (Conceptual Outline)

1. src/components/[Link]:
o Fetch quiz details and questions/options for a given quiz_id.
o Display questions with their options (e.g., radio buttons for multiple choice).
o useState to store selected answers.
o "Submit Quiz" button.
o On submit, send answers to a Django API endpoint (Submission creation).
o (Optional) Display score/feedback from the backend response.

Module 9: Developing an Inventory Management System

Assignment 9.1: Inventory Backend Models & API - Completion (Conceptual Outline)

1. Models (inventory_app/[Link]):

Python

from [Link] import models


from [Link] import User

class Item([Link]):
name = [Link](max_length=255)
sku = [Link](max_length=100, unique=True)
description = [Link](blank=True, null=True)
quantity = [Link](default=0)
price = [Link](max_digits=10, decimal_places=2)
location = [Link](max_length=255, blank=True,
null=True) # e.g., "Warehouse A, Shelf 3"
created_at = [Link](auto_now_add=True)
updated_at = [Link](auto_now=True)
def __str__(self):
return [Link]

class Supplier([Link]):
name = [Link](max_length=255)
contact_person = [Link](max_length=255, blank=True,
null=True)
email = [Link](blank=True, null=True)
phone = [Link](max_length=20, blank=True, null=True)
address = [Link](blank=True, null=True)

def __str__(self):
return [Link]

class PurchaseOrder([Link]):
supplier = [Link](Supplier, on_delete=models.SET_NULL,
null=True, blank=True)
order_date = [Link](auto_now_add=True)
expected_delivery_date = [Link](null=True, blank=True)
is_received = [Link](default=False)
# total_amount = [Link](max_digits=10,
decimal_places=2, default=0.00) # Can be calculated

def __str__(self):
return f"PO-{[Link]} from {[Link] if
[Link] else 'N/A'}"

class PurchaseOrderItem([Link]):
order = [Link](PurchaseOrder,
on_delete=[Link], related_name='items')
item = [Link](Item, on_delete=[Link])
quantity = [Link]()
unit_price = [Link](max_digits=10, decimal_places=2)

def __str__(self):
return f"{[Link]} of {[Link]} for PO-
{[Link]}"

class SaleOrder([Link]):
customer_name = [Link](max_length=255, blank=True,
null=True) # Or ForeignKey to User
order_date = [Link](auto_now_add=True)
is_fulfilled = [Link](default=False)

def __str__(self):
return f"SO-{[Link]} for {self.customer_name if
self.customer_name else 'N/A'}"

class SaleOrderItem([Link]):
order = [Link](SaleOrder, on_delete=[Link],
related_name='items')
item = [Link](Item, on_delete=[Link])
quantity = [Link]()
unit_price = [Link](max_digits=10, decimal_places=2)

def __str__(self):
return f"{[Link]} of {[Link]} for SO-
{[Link]}"

2. Serializers and Views: Create DRF serializers and generics views for all models.
o Inventory Update Logic (in views/serializers):
 When PurchaseOrderItem is created/updated, increment
[Link].
 When SaleOrderItem is created/updated, decrement [Link].
Add validation to prevent negative stock.
o Permission: Typically, only authenticated staff/admin users should manage
inventory.

Assignment 9.2: Item Listing and Stock Management Frontend - Completion


(Conceptual Outline)

1. src/components/[Link]:
o Fetch Item data from your Django API.
o Display a table/list of items with Name, SKU, Quantity, Price, Location.
o "Edit" and "Delete" buttons for each item (requires authentication).
o Input field for manual quantity adjustment (e.g., a "Restock" button next to
each item that opens a modal to add/subtract).
2. src/components/[Link]:
o A form to add new Items (Name, SKU, Quantity, Price, Location).
o Submission sends POST request to API.

Assignment 9.3: Simple Purchase Order Entry - Completion (Conceptual Outline)

1. src/components/[Link]:
o Dropdown to select an existing Supplier. Fetch suppliers from API.
o Dynamic fields to add PurchaseOrderItems:
 Dropdown to select an Item. Fetch items from API.
 Input for quantity.
 Input for unit_price.
 "Add Item to Order" button to add to local form state.
o Display a summary of items added to the current order.
o "Submit Purchase Order" button:
 On click, send a POST request to your PurchaseOrder API endpoint.
 The payload should include the supplier_id and a list of items (each
with item_id, quantity, unit_price). Your Django view will need to
process this to create PurchaseOrder and PurchaseOrderItems, then
update Item quantities.

Module 10: Deployment and Best Practices

Assignment 10.1: Prepare for Production - Completion (Conceptual Outline)

1. Django [Link] changes:


o DEBUG = False
o ALLOWED_HOSTS = ['[Link]', '[Link]',
'your_server_ip']
o Configure DATABASES for your production database (e.g., PostgreSQL).
o Set SECRET_KEY to a secure, randomly generated string (use environment
variable).
o Configure static and media files:

Python

# Ensure these are correctly set for production


STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles' # Directory where
collectstatic gathers files

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

2. Run collectstatic:

Bash

python [Link] collectstatic

This gathers all static files into the STATIC_ROOT directory, ready to be served by a
web server like Nginx.

3. Build React Frontend:

Bash

npm run build

This creates a build folder (or dist depending on setup) containing the optimized,
production-ready React application files.

Assignment 10.2: Mini Deployment Plan - Completion (Example for Heroku)

Project: BlogSite (React Frontend, Django Backend)

Chosen Cloud Provider: Heroku (for simplicity of demonstration)

Deployment Steps:

1. Backend (Django):
o Requirements: Create [Link] (pip freeze >
[Link]).
o Procfile: Create a Procfile in the root of your Django project:
o web: gunicorn [Link] --log-file -

(If using Channels: web: daphne [Link]:application -p $PORT


-b [Link])

o Database: Provision a PostgreSQL database add-on on Heroku. Heroku


automatically sets DATABASE_URL.
o Static Files: Use whitenoise to serve static files in production (add to
[Link], configure in [Link]).
o Heroku CLI: Install Heroku CLI, log in.
o Create App: heroku create your-blog-backend-app
o Push Code: git push heroku main (ensure your Heroku remote is set up).
o Migrate Database: heroku run python [Link] migrate
o Create Superuser (if not already): heroku run python [Link]
createsuperuser
o Environment Variables: Set SECRET_KEY on Heroku dashboard.
2. Frontend (React):
o Build: Ensure npm run build is run locally to generate the optimized build
folder.
o Static Hosting: Use a service like Netlify or Vercel for the React frontend, as
they are well-suited for static site hosting.
o Create App: Connect your GitHub repository to Netlify/Vercel.
o Build Command: Set build command to npm install && npm run build.
o Publish Directory: Set publish directory to build.
o Environment Variables: If your React app needs to know the Django API
URL, set it as an environment variable in Netlify/Vercel (e.g.,
REACT_APP_API_URL = [Link]
[Link]/).
o CORS: Ensure your Django backend's CORS_ALLOWED_ORIGINS includes your
Netlify/Vercel frontend URL.
3. Connecting Them:
o The React frontend will make API requests to the deployed Django backend
URL (e.g., [Link]
o Ensure Django's CORS_ALLOWED_ORIGINS setting explicitly allows requests
from your deployed React frontend's domain.

Sources
Demandez à Gemini de créer un rapport de recherche détaillé sur ce sujet

You might also like