Day 4 AI bootcamp: E-Commerce Platform with Django

Creating an intelligent and user-friendly e-commerce platform involves leveraging advanced technologies to enhance customer experience and streamline operations. This comprehensive guide will walk you through developing an AI-enhanced e-commerce website using Django. We will cover essential features such as an AI-powered virtual stylist, product recommendation engine, secure authentication with OAuth2, integration of Stripe for payment processing, and managing both physical and digital products. Each section includes detailed instructions, code snippets, and practical insights to help you build and manage your online store effectively.
---
### Developing an AI-Powered Virtual Stylist for Direct Purchases
An AI-powered virtual stylist can significantly enhance the shopping experience by providing personalized fashion advice and outfit suggestions based on user preferences and current trends. By leveraging machine learning algorithms, you can build a system that analyzes user data to offer tailored recommendations, increasing user engagement and boosting sales.
#### Implementation Steps:
1. Set Up the Django Environment
Install Django and create a new project:
```bash
pip install django
django-admin startproject ai_ecommerce
cd ai_ecommerce
```
2. Create the Application
```bash
python manage.py startapp store
```
Add the app to `INSTALLED_APPS` in `settings.py`:
```python
INSTALLED_APPS = [
# ...
'store',
# ...
]
```
3. Define User Profile and Product Models
In `store/models.py`, create models to store user preferences, fashion items, and user interactions:
```python
# store/models.py
from django.db import models
from django.contrib.auth.models import User
class StylePreference(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
styles = models.TextField()
sizes = models.CharField(max_length=50)
colors = models.TextField()
def __str__(self):
return f"{self.user.username}'s Preferences"
class FashionItem(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='fashion_items/')
category = models.CharField(max_length=50)
styles = models.TextField()
sizes = models.CharField(max_length=50)
colors = models.TextField()
def __str__(self):
return self.name
```
4. Integrate Machine Learning Models
Create a separate module, `recommender.py`, for the recommendation engine:
```python
# store/recommender.py
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
def recommend_outfits(user_preferences, fashion_items):
# Convert data to DataFrame
items_df = pd.DataFrame(list(fashion_items.values()))
# Combine relevant features
items_df['features'] = items_df['styles'] + ' ' + items_df['sizes'] + ' ' + items_df['colors']
# Vectorize features
vectorizer = TfidfVectorizer()
item_vectors = vectorizer.fit_transform(items_df['features'])
# Vectorize user preferences
user_vector = vectorizer.transform([user_preferences])
# Compute similarity
similarity = cosine_similarity(user_vector, item_vectors)
# Get top recommendations
recommendations = similarity.argsort()[0][-5:]
return items_df.iloc[recommendations]
```
5. Create Views for Recommendations
In `store/views.py`, develop views to handle user interactions and display recommended products:
```python
# store/views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from .models import StylePreference, FashionItem
from .recommender import recommend_outfits
@login_required
def virtual_stylist(request):
user_pref = StylePreference.objects.get(user=request.user)
fashion_items = FashionItem.objects.all()
recommendations = recommend_outfits(
f"{user_pref.styles} {user_pref.sizes} {user_pref.colors}",
fashion_items
)
return render(request, 'store/recommendations.html', {'recommendations': recommendations})
```
6. Implement Direct Purchase Functionality
Allow users to purchase recommended items seamlessly:
```python
# store/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('stylist/', views.virtual_stylist, name='virtual_stylist'),
path('product/<int:pk>/', views.product_detail, name='product_detail'),
path('add_to_cart/<int:product_id>/', views.add_to_cart, name='add_to_cart'),
# ... other URLs
]
# store/views.py
def product_detail(request, pk):
product = FashionItem.objects.get(pk=pk)
return render(request, 'store/product_detail.html', {'product': product})
def add_to_cart(request, product_id):
# Logic to add the product to the user's shopping cart
pass
```
#### Workflow Diagram:
- User Data Input ➔ Data Processing ➔ Model Inference ➔ Recommendation Display ➔ Direct Purchase
---
### Creating a Product Recommendation Engine in Django
A product recommendation engine enhances user experience by suggesting items based on browsing history and preferences. Implementing such a system involves analyzing user behavior and leveraging collaborative filtering techniques.
#### Implementation Steps:
1. Data Collection
Track user interactions using middleware or signals:
```python
# store/middleware.py
from django.utils import timezone
from .models import UserActivity
class UserActivityMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if request.user.is_authenticated:
UserActivity.objects.create(user=request.user, path=request.path, timestamp=timezone.now())
return response
```
2. Define User Activity Model
```python
# store/models.py
class UserActivity(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
path = models.CharField(max_length=200)
timestamp = models.DateTimeField()
```
3. Build the Recommendation Model
Implement collaborative filtering using the collected data:
```python
# store/recommendation_engine.py
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
def generate_recommendations(user_id):
# Load user activity data
activities = UserActivity.objects.values()
df = pd.DataFrame(activities)
# Create user-item interaction matrix
# Compute similarity and generate recommendations
# Return recommended product IDs
pass
```
4. Integrate with Django Views
Display recommendations on the user's homepage or product pages:
```python
# store/views.py
@login_required
def homepage(request):
recommendations = generate_recommendations(request.user.id)
products = FashionItem.objects.filter(id__in=recommendations)
return render(request, 'store/homepage.html', {'products': products})
```
---
### Implementing OAuth2 for Secure Authentication in Django
Secure authentication enhances user trust and protects sensitive information. Integrating OAuth2 allows users to log in using their social accounts, providing a seamless experience.
#### Implementation Steps:
1. Install and Configure Django Allauth
```bash
pip install django-allauth
```
Update `settings.py`:
```python
INSTALLED_APPS = [
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
# ... other apps
]
SITE_ID = 1
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
MIDDLEWARE = [
# ... existing middleware ...
'django.contrib.auth.middleware.AuthenticationMiddleware',
# ... other middleware ...
]
LOGIN_REDIRECT_URL = '/'
```
2. Set Up Social Application Credentials
- Register your application with Google Developers Console.
- Obtain the Client ID and Client Secret.
- Add a Social Application in Django admin with obtained credentials.
3. Configure URLs and Templates
```python
# ai_ecommerce/urls.py
from django.urls import path, include
urlpatterns = [
path('accounts/', include('allauth.urls')),
path('', include('store.urls')),
]
```
In your templates, provide login options:
```html
<!-- templates/base.html -->
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }} | <a href="{% url 'account_logout' %}">Logout</a></p>
{% else %}
<a href="{% url 'account_login' %}">Login</a>
{% endif %}
```
---
### Integrating Stripe for Secure Payment Processing
Stripe is a leading payment processing platform that provides a secure and user-friendly checkout experience. By integrating Stripe into your Django application, you can handle transactions efficiently.
#### Implementation Steps:
1. Install Stripe Library
```bash
pip install stripe
```
2. Configure Stripe Settings
In `settings.py`, add your Stripe API keys:
```python
STRIPE_PUBLIC_KEY = 'your_stripe_public_key'
STRIPE_SECRET_KEY = 'your_stripe_secret_key'
```
3. Create Order and OrderItem Models
```python
# store/models.py
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
created = models.DateTimeField(auto_now_add=True)
is_paid = models.BooleanField(default=False)
total_amount = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return f'Order {self.id}'
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items')
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField()
```
4. Implement the Checkout View
```python
# store/views.py
import stripe
from django.conf import settings
stripe.api_key = settings.STRIPE_SECRET_KEY
from .cart import Cart
def checkout(request):
cart = Cart(request)
total = int(cart.get_total_price() * 100) # Stripe expects amount in cents
if request.method == 'POST':
customer = stripe.Customer.create(
email=request.user.email,
source=request.POST['stripeToken']
)
charge = stripe.Charge.create(
customer=customer.id,
amount=total,
currency='usd',
description='E-Commerce Purchase'
)
# Process the order
order = Order.objects.create(user=request.user, is_paid=True, total_amount=cart.get_total_price())
for item in cart:
OrderItem.objects.create(
order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity']
)
# Update stock and clear cart
for item in cart:
product = item['product']
product.stock -= item['quantity']
product.save()
cart.clear()
return render(request, 'store/payment_success.html', {'order': order})
else:
return render(request, 'store/checkout.html', {'stripe_public_key': settings.STRIPE_PUBLIC_KEY})
```
5. Create the Checkout Template
```html
<!-- templates/store/checkout.html -->
{% extends 'base.html' %}
{% block content %}
<h2>Checkout</h2>
<form action="{% url 'checkout' %}" method="post">
{% csrf_token %}
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripe_public_key }}"
data-amount="{{ cart.get_total_price|floatformat:2|add:'0'|floatformat:0 }}"
data-name="E-Commerce Store"
data-description="Purchase"
data-email="{{ user.email }}"
data-locale="auto"
data-currency="usd">
</script>
</form>
{% endblock %}
```
---
### Managing Products and Categories
Efficient product management is essential for any online store. As the store owner, you can upload products with prices and pictures, organize them into categories, and manage inventory.
#### Implementation Steps:
1. Define Category and Product Models
(Already defined in previous steps)
2. Enable Product Management via Django Admin
```python
# store/admin.py
from django.contrib import admin
from .models import Product, Category, StylePreference, Order, OrderItem
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'category', 'price', 'stock', 'is_digital')
list_filter = ('category', 'is_digital')
search_fields = ('name', 'description')
admin.site.register(Product, ProductAdmin)
admin.site.register(Category)
admin.site.register(Order)
admin.site.register(OrderItem)
```
In the admin interface, you can:
- Add New Products: Upload images, set prices, and manage stock levels.
- Update Existing Products: Modify product details and adjust inventory.
- Manage Categories: Organize products for better user navigation.
---
### Implementing the Shopping Cart Functionality
A shopping cart allows users to select products, review their choices, and proceed to checkout.
#### Implementation Steps:
1. Create Cart Functionality
```python
# store/cart.py
from decimal import Decimal
from django.conf import settings
from .models import Product
class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get('cart')
if not cart:
cart = self.session['cart'] = {}
self.cart = cart
def add(self, product, quantity=1, override_quantity=False):
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0, 'price': str(product.get_price())}
if override_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
self.session.modified = True
def remove(self, product):
product_id = str(product.id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def __iter__(self):
product_ids = self.cart.keys()
products = Product.objects.filter(id__in=product_ids)
for product in products:
self.cart[str(product.id)]['product'] = product
for item in self.cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
def clear(self):
del self.session['cart']
self.save()
```
2. Create Cart Views
```python
# store/views.py
from .cart import Cart
def cart_add(request, product_id):
cart = Cart(request)
product = Product.objects.get(id=product_id)
cart.add(product=product)
return redirect('cart_detail')
def cart_remove(request, product_id):
cart = Cart(request)
product = Product.objects.get(id=product_id)
cart.remove(product)
return redirect('cart_detail')
def cart_detail(request):
cart = Cart(request)
return render(request, 'store/cart_detail.html', {'cart': cart})
```
3. Create Cart Template
```html
<!-- templates/store/cart_detail.html -->
{% extends 'base.html' %}
{% block content %}
<h2>Your Shopping Cart</h2>
{% if cart %}
<table>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th></th>
</tr>
{% for item in cart %}
<tr>
<td>{{ item.product.name }}</td>
<td>{{ item.quantity }}</td>
<td>{{ item.price }}</td>
<td>{{ item.total_price }}</td>
<td><a href="{% url 'cart_remove' item.product.id %}">Remove</a></td>
</tr>
{% endfor %}
</table>
<p>Total: {{ cart.get_total_price }}</p>
<a href="{% url 'checkout' %}">Proceed to Checkout</a>
{% else %}
<p>Your cart is empty.</p>
{% endif %}
{% endblock %}
```
---
### Managing Digital Products and Immediate Delivery
For digital products like e-books or software, you need to provide samples and ensure customers receive the full product immediately after purchase.
#### Implementation Steps:
1. Extend the Product Model for Digital Goods
```python
# store/models.py
class Product(models.Model):
# ... existing fields ...
is_digital = models.BooleanField(default=False)
digital_file = models.FileField(upload_to='digital_products/', null=True, blank=True)
sample_file = models.FileField(upload_to='digital_samples/', null=True, blank=True)
```
2. Configure Media Files
```python
# settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
```
3. Provide Downloadable Samples
In your product detail template:
```html
<!-- templates/store/product_detail.html -->
{% if product.is_digital and product.sample_file %}
<a href="{{ product.sample_file.url }}">Download Sample</a>
{% endif %}
```
4. Deliver Full Digital Products After Purchase
- Update Order Processing: Ensure `is_paid` is set to `True` after payment.
- Provide Access to Digital Products:
```python
# store/views.py
from django.contrib.auth.decorators import login_required
@login_required
def my_downloads(request):
orders = Order.objects.filter(user=request.user, is_paid=True)
digital_items = []
for order in orders:
for item in order.items.all():
if item.product.is_digital:
digital_items.append(item.product)
return render(request, 'store/my_downloads.html', {'digital_items': digital_items})
@login_required
def download_product(request, product_id):
product = Product.objects.get(id=product_id, is_digital=True)
orders = Order.objects.filter(user=request.user, is_paid=True, items__product=product)
if orders.exists():
file_path = product.digital_file.path
with open(file_path, 'rb') as f:
response = HttpResponse(f.read(), content_type='application/octet-stream')
response['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"'
return response
else:
raise Http404("You do not have access to this file.")
```
- Update URLs:
```python
# store/urls.py
urlpatterns = [
# ... existing patterns ...
path('my-downloads/', views.my_downloads, name='my_downloads'),
path('download/<int:product_id>/', views.download_product, name='download_product'),
]
```
---
### Recommended Resources for Further Study
- "Django for Professionals: Production websites with Python & Django" by William S. Vincent
*An in-depth guide to building advanced Django applications suitable for production environments, covering testing, security, and performance optimization.*
[Purchase on Amazon](https://www.amazon.com/Django-Professionals-Production-websites-Python/dp/1087533869/?tag=youraffiliatetag)
- "Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow" by Aurélien Géron
*A comprehensive guide to machine learning with practical examples, ideal for integrating AI into your Django projects.*
[Purchase on Amazon](https://www.amazon.com/Hands-Machine-Learning-Scikit-Learn-TensorFlow/dp/1492032646/?tag=youraffiliatetag)
- "Test-Driven Development with Python: Obey the Testing Goat using Django, Selenium, and JavaScript" by Harry J.W. Percival
*Learn how to build reliable applications using test-driven development practices, essential for maintaining e-commerce platforms.*
[Purchase on Amazon](https://www.amazon.com/Test-Driven-Development-Python-Selenium-JavaScript/dp/1491958707/?tag=youraffiliatetag)
- Web Hosting with Interserver
For reliable hosting solutions optimized for Django applications, consider [Interserver](https://www.interserver.net/r/your_affiliate_id). They offer scalable plans suitable for e-commerce platforms.
- Security Solutions with Sucuri
Enhance your site's security with [Sucuri](https://sucuri.net/?aff=your_affiliate_id), providing comprehensive website security solutions to protect against threats.
- Marketing Services with 24-7PressRelease
Boost your platform's visibility using [24-7PressRelease](https://www.24-7pressrelease.com/affiliate/your_affiliate_id) to distribute press releases and reach a wider audience.
---
### Key Takeaways
- Personalization Enhances User Experience: Implementing features like AI-powered virtual stylists and recommendation engines can significantly increase user engagement and sales.
- Security is Paramount: Integrate secure authentication with OAuth2 and use trusted payment gateways like Stripe to protect user data and transactions.
- Efficient Product Management: Utilize Django's models and admin interface to manage products, categories, and inventory effectively.
- Digital Product Handling: Extend your platform to manage digital goods, providing samples and immediate access post-purchase.
- Automation Improves Efficiency: Use tools like Celery for background tasks and AI for testing to streamline operations and ensure reliability.
Comments
Please log in to leave a comment.
No comments yet.