Backend Development in an E-commerce Systems with Stripe Integration.
Brandon Opere
|Tech Innovation| Founder & CEO | Software Eng | Product Design | Tech Author | Instructor | Partnership Advocate |
Backend development forms the backbone of any e-commerce system, providing essential functionalities such as data management, user authentication, order processing, and security. This guide covers the key aspects of backend development using Django ORM for defining database schemas, creating RESTful APIs for frontend interaction, building custom admin panels, integrating payment gateways, implementing search functionality, and ensuring security.
Models: Defining the Database Schema Using Django ORM
What is Django ORM?
Django ORM (Object-Relational Mapping) is a powerful and efficient tool provided by the Django web framework. It allows developers to interact with the database using Python code instead of writing raw SQL queries. Django ORM supports various databases, including PostgreSQL, MySQL, SQLite, and Oracle.
Defining Models for an E-commerce System
Example Models (Python with Django ORM)
from django.db import models
from django.contrib.auth.models import AbstractUser
# User model
class User(AbstractUser):
email = models.EmailField(unique=True)
# Category model
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
def __str__(self):
return self.name
# Product model
class Product(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.IntegerField()
category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
# Order model
class Order(models.Model):
user = models.ForeignKey(User, related_name='orders', on_delete=models.CASCADE)
total_price = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=20, choices=[
('Pending', 'Pending'),
('Shipped', 'Shipped'),
('Delivered', 'Delivered'),
])
def __str__(self):
return f"Order {self.id} by {self.user.username}"
# OrderItem model
class OrderItem(models.Model):
order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)
product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE)
quantity = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return f"{self.quantity} of {self.product.name}"
# Review model
class Review(models.Model):
product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE)
rating = models.IntegerField(choices=[(i, str(i)) for i in range(1, 6)])
comment = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"Review by {self.user.username} for {self.product.name}"
Best Practices for Defining Models
APIs: RESTful Endpoints for Frontend Interaction
What is a RESTful API?
A RESTful API (Representational State Transfer) is an architectural style for designing networked applications. It uses HTTP requests to perform CRUD (Create, Read, Update, Delete) operations on resources, typically represented in JSON format.
Creating RESTful APIs with Django and Django REST Framework (DRF)
Django REST Framework (DRF) is a powerful toolkit for building Web APIs in Django. It provides features like serialization, authentication, and viewsets, making it easier to create RESTful endpoints.
Example API Endpoints
Example API Implementation (Python with DRF)
from rest_framework import serializers
from .models import User, Product, Order, OrderItem, Review, Category
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email', 'first_name', 'last_name']
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'name', 'description', 'price', 'stock', 'category', 'created_at']
class OrderItemSerializer(serializers.ModelSerializer):
class Meta:
model = OrderItem
fields = ['id', 'product', 'quantity', 'price']
class OrderSerializer(serializers.ModelSerializer):
items = OrderItemSerializer(many=True, read_only=True)
class Meta:
model = Order
fields = ['id', 'user', 'total_price', 'created_at', 'status', 'items']
class ReviewSerializer(serializers.ModelSerializer):
class Meta:
model = Review
fields = ['id', 'product', 'user', 'rating', 'comment', 'created_at']
class CategorySerializer(serializers.ModelSerializer):
products = ProductSerializer(many=True, read_only=True)
class Meta:
model = Category
fields = ['id', 'name', 'description', 'products']
from rest_framework import viewsets, permissions
from .models import User, Product, Order, Review, Category
from .serializers import UserSerializer, ProductSerializer, OrderSerializer, ReviewSerializer, CategorySerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = [permissions.AllowAny]
class OrderViewSet(viewsets.ModelViewSet):
queryset = Order.objects.all()
serializer_class = OrderSerializer
permission_classes = [permissions.IsAuthenticated]
class ReviewViewSet(viewsets.ModelViewSet):
queryset = Review.objects.all()
serializer_class = ReviewSerializer
permission_classes = [permissions.IsAuthenticated]
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.all()
serializer_class = CategorySerializer
permission_classes = [permissions.AllowAny]
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import UserViewSet, ProductViewSet, OrderViewSet, ReviewViewSet, CategoryViewSet
router = DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'products', ProductViewSet)
router.register(r'orders', OrderViewSet)
router.register(r'reviews', ReviewViewSet)
router.register(r'categories', CategoryViewSet)
urlpatterns = [
path('', include(router.urls)),
]
Best Practices for Building APIs
Admin Panel: Custom Admin Interfaces for Managing the E-commerce System
领英推荐
What is an Admin Panel?
An admin panel is a web interface that allows administrators to manage the e-commerce system. This includes tasks such as managing products, orders, users, and reviews. Django’s built-in admin panel provides a powerful and customizable interface for managing database models.
Customizing the Django Admin Panel
from django.contrib import admin
from .models import User, Product, Order, OrderItem, Review, Category
admin.site.register(User)
admin.site.register(Product)
admin.site.register(Order)
admin.site.register(OrderItem)
admin.site.register(Review)
admin.site.register(Category)
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'price', 'stock', 'category', 'created_at')
search_fields = ('name', 'category__name')
list_filter = ('category',)
admin.site.register(Product, ProductAdmin)
class OrderAdmin(admin.ModelAdmin):
list_display = ('id', 'user', 'total_price', 'status', 'created_at')
list_filter = ('status',)
date_hierarchy = 'created_at'
admin.site.register(Order, OrderAdmin)
class OrderItemInline(admin.TabularInline):
model = OrderItem
extra = 0
class OrderAdmin(admin.ModelAdmin):
inlines = [OrderItemInline]
admin.site.register(Order, OrderAdmin)
def mark_as_shipped(modeladmin, request, queryset):
queryset.update(status='Shipped')
mark_as_shipped.short_description = "Mark selected orders as shipped"
class OrderAdmin(admin.ModelAdmin):
actions = [mark_as_shipped]
admin.site.register(Order, OrderAdmin)
Best Practices for Admin Panel
Payment Integration: Secure Payment Gateways for Processing Transactions
What is Payment Integration?
Payment integration involves incorporating third-party payment gateways into the e-commerce system to process transactions securely. Common payment gateways include Stripe, PayPal, and Square. Integrating these services allows customers to make payments using credit cards, debit cards, and other payment methods.
Integrating Stripe with Django
pip install stripe
# settings.py
STRIPE_PUBLIC_KEY = 'your-public-key'
STRIPE_SECRET_KEY = 'your-secret-key'
import stripe
from django.conf import settings
from django.views import View
from django.http import JsonResponse
stripe.api_key = settings.STRIPE_SECRET_KEY
class CreatePaymentIntentView(View):
def post(self, request, *args, **kwargs):
data = json.loads(request.body)
try:
intent = stripe.PaymentIntent.create(
amount=data['amount'],
currency='usd',
payment_method_types=['card'],
)
return JsonResponse({'client_secret': intent['client_secret']})
except Exception as e:
return JsonResponse({'error': str(e)}, status=400)
// Assuming you have included Stripe.js in your HTML
const stripe = Stripe('your-public-key');
document.getElementById('checkout-button').addEventListener('click', async () => {
const response = await fetch('/create-payment-intent/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ amount: 1000 }) // Amount in cents
});
const { client_secret } = await response.json();
const result = await stripe.confirmCardPayment(client_secret, {
payment_method: {
card: elements.create('card'),
billing_details: {
name: 'Jenny Rosen',
},
}
});
if (result.error) {
// Show error to your customer
console.log(result.error.message);
} else {
// The payment has been processed!
if (result.paymentIntent.status === 'succeeded') {
console.log('Payment succeeded!');
}
}
});
Best Practices for Payment Integration