📅  最后修改于: 2023-12-03 15:14:43.108000             🧑  作者: Mango
In this tutorial, we will create a web application using Django that emulates some of the functionalities of the popular online store, Amazon. We will cover the following topics:
To follow along with this tutorial, you should have the following:
The first step is to create a new Django project. In your terminal, navigate to the directory where you want to create the project and run the following command:
django-admin startproject amazon_like
This will create a new directory called amazon_like
with the basic structure of a Django project.
The next step is to define the models for our products and users. Open the models.py
file in the amazon_like
directory and add the following code:
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2)
image = models.ImageField(upload_to='products/')
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
products = models.ManyToManyField(Product)
total = models.DecimalField(max_digits=8, decimal_places=2)
created = models.DateTimeField(auto_now_add=True)
paid = models.BooleanField(default=False)
We have defined two models, Product
and Order
. The Product
model has fields for the name, description, price, and image of a product. The Order
model has a foreign key to the User
model, a many-to-many relationship with products, a total field, and created and paid fields for keeping track of order status.
Next, we will create views for displaying lists of products and individual product detail pages. Open the views.py
file in the amazon_like
directory and add the following code:
from django.shortcuts import render, get_object_or_404
from .models import Product
def product_list(request):
products = Product.objects.all()
context = {'products': products}
return render(request, 'amazon_like/product_list.html', context)
def product_detail(request, id):
product = get_object_or_404(Product, id=id)
context = {'product': product}
return render(request, 'amazon_like/product_detail.html', context)
We have defined two views, product_list
and product_detail
. The product_list
view retrieves all the products and passes them to a template for display. The product_detail
view retrieves a single product by its id and passes it to a template for display.
Now, we will add a shopping cart and checkout process to our application. We will create a new app called cart
to encapsulate this functionality. Run the following command in your terminal:
python manage.py startapp cart
Next, open the views.py
file in the cart
directory and add the following code:
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from amazon_like.models import Product
from .cart import Cart
from .forms import CartAddProductForm
@require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product,
quantity=cd['quantity'],
update_quantity=cd['update'])
return redirect('cart:cart_detail')
def cart_remove(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
cart.remove(product)
return redirect('cart:cart_detail')
def cart_detail(request):
cart = Cart(request)
return render(request, 'cart/cart_detail.html', {'cart': cart})
We have defined three views, cart_add
, cart_remove
, and cart_detail
. The cart_add
view adds a product to the cart, with an option to update the quantity of an existing product or add a new product. The cart_remove
view removes a product from the cart. The cart_detail
view displays the contents of the cart.
Finally, we will integrate our application with a payment gateway to enable users to make purchases. We will use the Stripe payment gateway for this purpose. First, install the Stripe Python package by running the following command:
pip install stripe
Next, open the views.py
file in the cart
directory and add the following code:
import stripe
from django.conf import settings
from django.contrib.auth.decorators import login_required
stripe.api_key = settings.STRIPE_SECRET_KEY
@login_required
def checkout(request):
cart = Cart(request)
if request.method == 'POST':
try:
token = request.POST['stripeToken']
charge = stripe.Charge.create(
amount=int(cart.get_total_price() * 100),
currency='usd',
description='Amazon-like App',
source=token,
)
order = Order.objects.create(
user=request.user,
total=cart.get_total_price(),
)
for item in cart:
OrderProduct.objects.create(
order=order,
product=item['product'],
quantity=item['quantity']
)
cart.clear()
return render(request, 'cart/checkout_done.html', {'order': order})
except stripe.error.CardError as e:
error = e.json_body['error']
return render(request, 'cart/checkout.html', {'error': error})
else:
form = StripeCheckoutForm()
return render(request, 'cart/checkout.html', {'cart': cart, 'form': form})
We have defined a view called checkout
that processes the payment via Stripe. If the payment is successful, the order is created, and the user is redirected to a thank-you page. If the payment fails, the user is redirected back to the checkout page with an error message.
In this tutorial, we have created a Django web application that emulates some of the functionalities of Amazon, including product listings, individual product pages, shopping cart, and checkout process. We have also integrated the application with the Stripe payment gateway to enable users to make purchases. This is just a starting point, and there are many more features that can be added to make this application even more robust and functional.