×
Community Blog Develop a Cart Application with Django

Develop a Cart Application with Django

This tutorial is the second article in our series on building an e-commerce app using the Django web framework.

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.

1. Introduction

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

2. Scope of Our Project

2.1. Project Details

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).

2.2. The Cart Application

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:

  • Buy and Sell options
  • Cart and CartItems of the client
  • Adding, updating and removing Products to the Cart

2.3. Setting Up the Development Environment

We will start by getting the source code of the project that is already online :

  • We clone the project using GIT
$ 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.

  • make sure all the required packages are installed (Take a look at the previous tutorial setup tools section): Python3.6, Pip, Virtualenv, libpq-dev, postgresql, postgresql-contrib
  • Install virtualenv
$ pip install virtualenv
  • Create a venv
$ virtualenv venv
  • Activate the venv
$ source venv\bin\activate
  • Install the dependencies
(venv)$ pip install -r requirements.txt
  • Initialize the database
(venv)$ python manage.py migrate
  • Create a super user
(venv)$ python manage.py createsuperuser  # then follow the instructions
  • Test if everything is working well
(venv)$ python manage.py runserver

3. Develop the Cart App

We will follow this process:

  • Initialize the app
  • Define the database models inside the models.py file
  • Define the views that will handled requests inside views.py
  • Define the routes that users will follow to navigate through our applications using urls.py file.
  • Define the admin interface configurations that will help the application administrator to effortlessly manage the entities stored on the database using admin.py file
  • We will then customize our templates to look prettier

3.1. Initialize the App

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,
    ...
] 
...

3.2. Defining the Models

As mentioned above, this app will handle the following models:

  • Cart
  • CartItem

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

3.3. Defining the Views

3.3.1. The Views

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'

3.4. Defining the Url Routes

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'),
]

3.5. Define Admin Interface

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

3.6. Testing that Everything Is Working Well

(venv)$ cd buyansell
(venv)$ python manage.py runserver

Then, poen your browser to this location:

http://localhost:8000

4. Conclusion

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.

2 1 0
Share on

Alibaba Clouder

2,599 posts | 764 followers

You may also like

Comments

5177461397045736 June 24, 2019 at 5:25 pm

Instance of 'CartItem' has no 'client' member. Where I find out client variable?

binel237 April 20, 2020 at 4:35 pm

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