You are on page 1of 1

How to Create a Fully Functional E-

commerce Website with Django


Step 2 of 5: Make an Order

Andika Pratama · Follow


Published in Analytics Vidhya · 4 min read · Feb 10, 2020

71 1

https://www.shuup.com/wp-content/uploads/2017/12/python-plus-django-1.jpg

Prerequisites
Django Latest Version

Anaconda (Optional) to make Virtual Environment

Visual Studio Code (Optional) ad Code Editor

Before starting the tutorial don’t forget to activate your Virtual Environment,
and the project we created in the previous tutorial. If yo not you can
download it here:

Andika7/DjangoEcommerce
Contribute to Andika7/DjangoEcommerce development by creating
an account on GitHub.
github.com

A. Create Databases in Models


Before we start to make an order. the first thing to do is create a database
that will store order data

For starters we will make 3 data tables namely:


- Item will store product data
- OrderItem will store product data that you want to order
- Order will store order information

To create a database in Django framework, we will use models.py file which


is in the core directory, open file with your code editor and proceed with this
tutorial.

1. Import

from django.conf import settings


from django.db import models
from django.shortcuts import reverse

2. Add Item model

1 CATEGORY = (
2 ('S', 'Shirt'),
3 ('SP', 'Sport Wear'),
4 ('OW', 'Out Wear')
5 )
6
7 LABEL = (
8 ('N', 'New'),
9 ('BS', 'Best Seller')
10 )
11
12 class Item(models.Model) :
13 item_name = models.CharField(max_length=100)
14 price = models.FloatField()
15 discount_price = models.FloatField(blank=True, null=True)
16 category = models.CharField(choices=CATEGORY, max_length=2)
17 label = models.CharField(choices=LABEL, max_length=2)
18 description = models.TextField()
19
20 def __str__(self):
21 return self.item_name
22
23 def get_absolute_url(self):
24 return reverse("core:product", kwargs={
25 "pk" : self.pk
26
27 })
28
29 def get_add_to_cart_url(self) :
30 return reverse("core:add-to-cart", kwargs={
31 "pk" : self.pk
32 })
33
34 def get_remove_from_cart_url(self) :
35 return reverse("core:remove-from-cart", kwargs={
36 "pk" : self.pk
37 })

ModelItem.py hosted with ❤ by GitHub view raw

In the item model you will see there are 3 additional functions, these
functions include:

get_absolute_url will return url from product

get_add_to_cart_url will return url to function add item to cart in


views.py file we will make

get_remove_from_cart_url will return url to function remove item from


cart in views.py file we will make

3. Add OrderItem model

1 class OrderItem(models.Model) :
2 user = models.ForeignKey(settings.AUTH_USER_MODEL,
3 on_delete=models.CASCADE)
4 ordered = models.BooleanField(default=False)
5 item = models.ForeignKey(Item, on_delete=models.CASCADE)
6 quantity = models.IntegerField(default=1)
7
8
9 def __str__(self):
10 return f"{self.quantity} of {self.item.item_name}"

ModelOrderItem.py hosted with ❤ by GitHub view raw

OrderItem stores data of the product you want to order and the amount of
the product

4. Add Order Model

1 class Order(models.Model) :
2 user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
3 items = models.ManyToManyField(OrderItem)
4 start_date = models.DateTimeField(auto_now_add=True)
5 ordered_date = models.DateTimeField()
6 ordered = models.BooleanField(default=False)
7
8 def __str__(self):
9 return self.user.username

ModelOreder.py hosted with ❤ by GitHub view raw

The Order model will store detailed information of the orders made, but in
this part of the tutorial we will not display complete order information, we
will add another field in the next part.

5. Register database to admin

open core/admin.py file witch code editor and fill with the code below :

from django.contrib import admin


from .models import Item, OrderItem, Order
admin.site.register(Item)
admin.site.register(OrderItem)
admin.site.register(Order)

That will register your database on the admin page. You can check it on the
admin page later

6 . Migrate model database

Migrate your model database with the command below :

$ python manage.py migrate


$ python manage.py makemigrations

Complete models.py code can be seen in the following link:

Andika7/DjangoEcommerce
Contribute to Andika7/DjangoEcommerce development by creating
an account on GitHub.
github.com

B. Managing Views
We have created a database and now it is our turn to manage and manage
our views. We will create 2 views that is HomeView and ProductView and 2
function that is add_to_cart() and remove_from_cart(). to continue open
core/views.py and continue with the following tutorial

1. Import

from django.contrib import messages


from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView
from django.utils import timezone
from .models import (
Item,
Order,
OrderItem
)

Import all the model classes that we have previously created into views.py

2. Add HomeView

In the previous tutorial article, we made a home function to display a view.


delete the home function and change it as Class View this :

class HomeView(ListView):
model = Item
template_name = "home.html

We use the Item model as a home model and home.html as template view.
home.html can be found at templates directory

3. Add ProductView

class ProductView(DetailView):
model = Item
template_name = "product.html"

We use the Item model as a home model and product.html as template view.
product.html can be found at templates directory

4. add_to_cart() function

1 def add_to_cart(request, pk) :


2 item = get_object_or_404(Item, pk = pk )
3 order_item, created = OrderItem.objects.get_or_create(
4 item=item,
5 user = request.user,
6 ordered = False
7 )
8 order_qs = Order.objects.filter(user=request.user, ordered= False)
9
10 if order_qs.exists() :
11 order = order_qs[0]
12
13 if order.items.filter(item__pk = item.pk).exists() :
14 order_item.quantity += 1
15 order_item.save()
16 messages.info(request, "Added quantity Item")
17 return redirect("core:product", pk = pk)
18 else:
19 order.items.add(order_item)
20 messages.info(request, "Item added to your cart")
21 return redirect("core:product", pk = pk)
22 else:
23 ordered_date = timezone.now()
24 order = Order.objects.create(user=request.user, ordered_date = ordered_date)
25 order.items.add(order_item)
26 messages.info(request, "Item added to your cart")
27 return redirect("core:product", pk = pk)

add_to_cart.py hosted with ❤ by GitHub view raw

This function will add your product to OrderItem database and add detail
order to Order database

5. remove_from_cart() function

1 def remove_from_cart(request, pk):


2 item = get_object_or_404(Item, pk=pk )
3 order_qs = Order.objects.filter(
4 user=request.user,
5 ordered=False
6 )
7 if order_qs.exists():
8 order = order_qs[0]
9 if order.items.filter(item__pk=item.pk).exists():
10 order_item = OrderItem.objects.filter(
11 item=item,
12 user=request.user,
13 ordered=False
14 )[0]
15 order_item.delete()
16 messages.info(request, "Item \""+order_item.item.item_name+"\" remove from your cart"
17 return redirect("core:product")
18 else:
19 messages.info(request, "This Item not in your cart")
20 return redirect("core:product", pk=pk)
21 else:
22 #add message doesnt have order
23 messages.info(request, "You do not have an Order")
24 return redirect("core:product", pk = pk)

remove_from_cart.py hosted with ❤ by GitHub view raw

This function will remove all your product from OrderItem database and
remove detail order from Order database

6. Update your templates directory

In templates directory we make some changes. So update your templates


directory from the following link :

Andika7/DjangoEcommerce
You can't perform that action at this time. You signed in with another
tab or window. You signed out in another tab or…
github.com

C. Managing Urls
After the view is finished, then the url will be managed where the view will
be displayed in the browser. Open your core/urls.py file and fill with the
code below :

1 from django.urls import path


2 from .views import (
3 remove_from_cart,
4 add_to_cart,
5 ProductView,
6 HomeView
7 )
8
9 app_name = 'core'
10
11 urlpatterns = [
12 path('', HomeView.as_view(), name='home'),
13 path('product/<pk>/', ProductView.as_view(), name='product'),
14 path('add-to-cart/<pk>/', add_to_cart, name='add-to-cart'),
15 path('remove-from-cart/<pk>/', remove_from_cart, name='remove-from-cart')
16 ]

urls.py hosted with ❤ by GitHub view raw

Import all view classes and functions and add the url for each view.

D. Demo Aplications
1. Run your server with the command below :

$ python manage.py runserver

2. open http://127.0.0.1:8000/ and choose one product, if you do not have a


product you can adding in admin page

Item Database

3. Click Add to cart button in product page and you will see the product will
add to your OrderItem and Order database

Order Database

4. Click remove from cart button to remove your current order. it will delete
order item from database Order and OrderItem

To this end the function to create an order has been implemented

Complete Source Code this Part :

Andika7/DjangoEcommerce
Contribute to Andika7/DjangoEcommerce development by creating
an account on GitHub.
github.com

Proceed to the next part!


I hope you’ve found the second part of this tutorial helpful. In the next
session, we’re going to make an Order Summary in our shopping cart.

Django Python Ecommerce

71 1

Written by Andika Pratama Follow

196 Followers · Writer for Analytics Vidhya

Fresh Graduate of Computer Science at Universitas Syiah Kuala, Software Engineer. Check
my github on github.com/Andika7

More from Andika Pratama and Analytics Vidhya

Andika Pratama in Analytics Vidhya Kia Eisinga in Analytics Vidhya

How to Create your own Search How to create a Python library


Engine with Python Language an… Ever wanted to create a Python library, albeit
Step 2 : Data Crawling Using Python Scrapy for your team at work or for some open…

5 min read · Jan 27, 2020 7 min read · Jan 26, 2020

1 2.4K 27

Hannan Satopay in Analytics Vidhya Andika Pratama in Analytics Vidhya

The Ultimate Markdown Guide (for How to Create your own Search
Jupyter Notebook) Engine with Python Language an…
An in-depth guide for Markdown syntax Step 4 : Implement Index and Query From
usage for Jupyter Notebook Python Language to Laravel Framework

10 min read · Nov 18, 2019 6 min read · Jan 28, 2020

2.2K 13 30 1

See all from Andika Pratama See all from Analytics Vidhya

Recommended from Medium

Laxfed Paulacy in Straight Bias Python Hellen Wainaina

PYTHON — Building a User Creating Mpesa Callback View and


Management System with Django… URL with Django Rest Framework.
First, solve the problem. Then, write the code. Introduction
— John Johnson

· 4 min read · 4 days ago 6 min read · Sep 22, 2023

35 17 1

Lists

Coding & Development Predictive Modeling w/


11 stories · 494 saves Python
20 stories · 987 saves

Practical Guides to Machine ChatGPT


Learning 21 stories · 507 saves
10 stories · 1178 saves

Akshat Gadodia Siddhant Bhattarai

Dockerizing a Django and MySQL Building a CI/CD Pipeline for a


Application: A Step-by-Step Guide Django-Based Web Application…
Docker has revolutionized the way we build, Introduction
ship, and run applications. It provides a…

3 min read · Sep 16, 2023 6 min read · Nov 12, 2023

36 6

Kerem Can ÇELEPKOLU Dolamu Oludare in Towards Data Engineering

Building with Django: Brick By Dockerize Your Databases: A Step-


Brick by-Step Guide to MySQL…
How to Use OpenAI APIs with Django In my last article, we went through the
concept of virtual machines and docker…

8 min read · Feb 17, 2024 7 min read · Oct 9, 2023

99 13 1

See more recommendations

Help Status About Careers Blog Privacy Terms Text to speech Teams

You might also like