By Bineli Manga, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.
With the emergence of new data technologies and new technology products, it is now a need for every business to build its own e-commerce platform and integrate it directly into the company website. The tutorial we are presenting you now has the objective to show you how you can leverage the power of the Django framework to build a cart system.
This tutorial is the second article in our series on building an e-commerce app with Django. If you missed out the first tutorial, you can find it online here: How to Develop Web Applications on Alibaba Cloud with Django Framework
The project we are building is an e-commerce application where people can buy or sell items. For flexibility and maintainability reasons, the project hast been split into three independent apps: the Core app (Developed on the previous tutorial), the Cart app (on this tutorial) and the Payment app (on the next one).
The cart application will be used to manage the buying and selling process, as well as the Cart itself with the CartItems inside it (adding, updating or removing CartItems).
The specific elements that will be managed here will be:
We will start by getting the source code of the project that is already online :
$ cd ~/projects # Switch to your project folder on Home directory
$ git clone https://github.com/binel01/buyandsell.git
NB: After issueing this command, a folder named buyandsell will be created on the project directory containing all the source code of our project.
$ pip install virtualenv
$ virtualenv venv
$ source venv\bin\activate
(venv)$ pip install -r requirements.txt
(venv)$ python manage.py migrate
(venv)$ python manage.py createsuperuser # then follow the instructions
(venv)$ python manage.py runserver
We will follow this process:
First, we need to create a new application called cart and add it to our settings.py config file.
(venv)$ django-admin startapp cart
This command will create a new folder named cart containing the source code of our cart application.
Adding cart app to our settings.py file
...
INSTALLED_APPS = [
...
cart,
...
]
...
As mentioned above, this app will handle the following models:
And here is the corresponding source code:
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from core.models import Product
class Cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(default=datetime.now)
class CartItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
price_ht = models.FloatField(blank=True)
cart = models.ForeignKey('Cart', on_delete=models.CASCADE)
TAX_AMOUNT = 19.25
def price_ttc(self):
return self.price_ht * (1 + TAX_AMOUNT/100.0)
def __str__(self):
return self.client + " - " + self.product
We have to define the views that will act as our controlelrs for managing the data presented to the users.
Here is the resulting views.py file for the Cart and CartItem database models:
from django.shortcuts import render
from django.views.generic import DetailView, ListView, CreateView, UpdateView, DeleteView
from .models import Cart, CartItem
##-------------- Cart Views --------------------------------------
class DetailCart(DetailView):
model = Cart
template_name='cart/detail_cart.html'
class ListCart(ListView):
model = Cart
context_object_name = 'carts'
template_name='cart/list_carts.html'
class CreateCart(CreateView):
model = Cart
template_name = 'cart/create_cart.html'
class Updatecart(UpdateView):
model = Cart
template_name = 'cart/update_cart.html'
class DeleteCart(DeleteView):
model = Cart
template_name = 'cart/delete_cart.html'
##-------------- CartItem Views --------------------------------------
class DetailCartItem(DetailView):
model = CartItem
template_name='cartitem/detail_cartitem.html'
class ListCartItem(ListView):
model = CartItem
context_object_name = 'cartitems'
template_name='cartitem/list_cartitems.html'
class CreateItemCart(CreateView):
model = CartItem
template_name = 'cartitem/create_cartitem.html'
class UpdateCartItem(UpdateView):
model = CartItem
template_name = 'cartitem/update_cartitem.html'
class DeleteCartItem(DeleteView):
model = Cart
template_name = 'cartitem/delete_cartitem.html'
Here are the url routes, defined in _buyandsell/cart/urls.py_:
from django.urls import path, include
from . import views
# Cart Urls
urlpatterns = [
path('cart/', views.ListCart, name='list-carts'),
path('cart/<int:pk>/', views.DetailCart.as_view(), name='detail-cart'),
path('cart/create/', views.CreateCart.as_view(), name='create-cart'),
path('cart/<int:pk>/update/', views.Updatecart.as_view(), name='update-cart'),
path('cart/<int:pk>/delete/', views.DeleteCart.as_view(), name='delete-cart'),
]
# CartItem Urls
urlpatterns += [
path('cartitem/', views.ListCartItem.as_view(), name='list-cartitem'),
path('cartitem/<int:pk>/', views.DetailCartItem.as_view(), name='detail-cartitem'),
path('cartitem/create/', views.CreateCartItem.as_view(), name='create-cartitem'),
path('cartitem/<int:pk>/update/', views.UpdateCartItem.as_view(), name='update-cartitem'),
path('cartitem/<int:pk>/delete/', views.DeleteCartItem.as_view(), name='delete-cartitem'),
]
Generally, when you build a web application to solve a business need of a client, you are also going to build a administrator application that will manage the data stored on the database, as well as access rights, permissions and roles. This is where Django simplifies the life of web developpers by allowing them to not worry about this tasks because it is already done by default.
In order to configure the admin interface, you have to modifiy the file: admin.py, and configure it to use our models.
Here is the resulting admin.py file:
from django.contrib import admin
# Register your models here.
class CartAdmin(admin.ModelAdmin):
pass
class CartItemAdmin(admin.ModelAdmin):
pass
(venv)$ cd buyansell
(venv)$ python manage.py runserver
Then, poen your browser to this location:
http://localhost:8000
By the end of this tutorial, you should be familiar on how to start building an application with the Django framework. More precisely, you have learned what Django models, views, and templates are.
The source code of the application used for this tutorial can be found here on GitHub page: https://github.com/binel01/buyandsell/tree/master/core
In the next part of this series of tutorials, I will show how to develop the Cart application, in order to manage the sales of your products.
How to Manage Django Images and Static Assets on Ubuntu 18.04
2,599 posts | 764 followers
FollowAlibaba Clouder - December 11, 2018
Alibaba Clouder - April 28, 2021
Alibaba Clouder - August 26, 2020
Alibaba Clouder - July 26, 2019
Alibaba Cloud Community - January 10, 2022
Alibaba Clouder - March 22, 2019
Hi,Thanks for asking this question.I think there is no need to add a reference to the 'client' inside this 'CartItem' model, because there is already a reference to it inside the 'Cart' model, through the member 'user' of the django model 'User'.Then, you can get access to the client of a CartItem through the chained reference:CartItem --> Cart --> User.Hope this makes things more clear for you.Don't hesitate to reach back here if you have any other question.BR,Bineli Arsene
2,599 posts | 764 followers
FollowElastic and secure virtual cloud servers to cater all your cloud hosting needs.
Learn MoreLearn More
A scalable and high-performance content delivery service for accelerated distribution of content to users across the globe
Learn MoreMore Posts by Alibaba Clouder
5177461397045736 June 24, 2019 at 5:25 pm
Instance of 'CartItem' has no 'client' member. Where I find out client variable?