[PYTHON] How to develop a cart app with Django

This tutorial is the second in a series on building ** e-commerce ** apps using the ** Django ** web framework. If you missed the first tutorial, you can find it online here. How to develop web applications on Alibaba Cloud using the Django framework (https://www.alibabacloud.com/blog/how-to-develop-web-applications-on-alibaba-cloud-with-django) -framework_594265? spm = a2c65.11461447.0.0.25d054951cPDkx)

1. Introduction

With the advent of new data and technology products, every business now needs to build its own e-commerce platform and integrate it directly into the company's website. This tutorial is intended to show you how to harness the power of the Django framework to build a cart system.

2. Scope of our project

** 2.1. Project details ** The project we are building is an e-commerce application that allows people to buy and sell goods. For flexibility and maintainability, the project is divided into three independent apps: Core app (developed in previous tutorial), Cart app (developed in this tutorial), Payment app (developed in next tutorial) ..

** 2.2. Cart application ** The cart application is used to manage the purchasing and selling process, and to manage the cart itself and the cart items in the cart (adding, updating, deleting cart items).

The specific elements managed here are:

--Purchase and sale options --Client carts and cart items --Add, update, or delete items in your cart

** 2.3. Development environment settings ** We start by getting the source code for a project that is already online.

--Clone the project using GIT.

$ cd ~/projects                 # Switch to your project folder on Home directory
$ git clone https://github.com/binel01/buyandsell.git

Note: After issuing this command, a folder named buyandsell will be created in your project directory to contain all the source code for your project.

--Make sure you have all the required packages installed. Python3.6, Pip, Virtualenv, libpq-dev, postgresql, postgresql-contrib --Install virtualenv

$ pip install virtualenv

--Create venv

$ virtualenv venv

--Activate venv

$ source venv\bin\activate

--Dependency installation

(venv)$ pip install -r requirements.txt

--Database initialization

(venv)$ python manage.py migrate

--Create a superuser

(venv)$ python manage.py createsuperuser  # then follow the instructions

--Test if everything is working.

(venv)$ python manage.py runserver

3. Development of cart app

We will proceed with this flow.

--App initialization -** Define the database model in the models.py ** file. -** Defines the views that handle the request in views.py **. -Use the ** urls.py ** file to define a route for users to navigate your application. -The ** admin.py ** file is used to define settings for the administrator interface to help application administrators manage entities stored in the database. ――After that, customize the template to make it look more cute.

3.1. App initialization

First, you need to create a new application called ** cart ** and add it to the ** settings.py ** configuration file.

(venv)$ django-admin startapp cart

This command creates a new folder named cart that contains the source code for the cart application.

Add the cart app to the settings.py file.

...
INSTALLED_APPS = [
    ...
    cart,
    ...
] 
...

3.2. Model definition

As mentioned above, this app supports the following models.

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. View definition

** 3.3.1. View ** In order to manage the data presented to the user, we have to define a view that acts as our control.

Below are the ** views.py ** files that result from 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. Url Route Definition

Here is the URL root 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. Definition of administrator interface

In general, when you build a web application to solve your client's business needs, you also build an administrator application that manages the data, permissions, permissions, and roles stored in the database. Django simplifies the life of web developers because this is already done by default.

To configure the admin interface, you must modify the ** admin.py ** file to configure it to use the model.

The resulting ** admin.py ** file is:

from django.contrib import admin

# Register your models here.
class CartAdmin(admin.ModelAdmin):
    pass

class CartItemAdmin(admin.ModelAdmin):
    pass

3.6. Testing if everything is working

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

Then move your browser to this location.

http://localhost:8000

4. Conclusion

By the end of this tutorial, you should know how to get started building your application with the Django framework. More precisely, you've learned what Django's models, views, and templates are.

The source code for the application used in this tutorial is on the GitHub page [https://github.com/binel01/buyandsell/tree/master/core](https://github.com/binel01/buyandsell/tree/master/ It is located at core? spm = a2c65.11461447.0.0.25d054951cPDkx).

The next part of the tutorial in this series will show you how to develop a cart application to manage product sales.

Recommended Posts

How to develop a cart app with Django
How to create a multi-platform app with kivy
Steps to develop Django with VSCode
How to get started with Django
How to authenticate with Django Part 2
How to authenticate with Django Part 3
How to deploy a web app made with Flask to Heroku
How to do arithmetic with Django template
How to add a package with PyCharm
Here's a brief summary of how to get started with Django
How to deploy a Django app on heroku in just 5 minutes
How to read a CSV file with Python 2/3
How to send a message to LINE with curl
How to draw a 2-axis graph with pyplot
How to make a dictionary with a hierarchical structure.
How to implement "named_scope" of RubyOnRails with Django
How to create a Rest Api in Django
I want to upload a Django app to heroku
A new form of app that works with GitHub: How to make GitHub Apps
How to convert / restore a string with [] in python
Create a Todo app with Django REST Framework + Angular
I tried to create a table only with Django
[Python] How to draw a line graph with Matplotlib
How to create a submenu with the [Blender] plugin
(Python) Try to develop a web application using Django
How to deploy a Django application on Alibaba Cloud
How to get a logged-in user with Django's forms.py
How to convert a class object to a dictionary with SQLAlchemy
How to make a shooting game with toio (Part 1)
Create a Todo app with the Django REST framework
How to build a Django (python) environment on docker
Steps from installing Python 3 to creating a Django app
Create a Todo app with Django ③ Create a task list page
How to use Django on Google App Engine / Python
Transit to the update screen with the Django a tag
Deploy a Django app made with PTVS on Azure
To myself as a Django beginner (1) --Create a project app--
[Python] How to create a 2D histogram with Matplotlib
How to run Django on IIS on a Windows server
How to reference static files in a Django project
To myself as a Django beginner (4) --Create a memo app--
Create a Todo app with Django ⑤ Create a task editing function
[Python] How to draw a scatter plot with Matplotlib
Deploy a web app created with Streamlit to Heroku
How to call a function
Create a homepage with django
How to update with SQLAlchemy?
How to cast with Theano
How to hack a terminal
How to Alter with SQLAlchemy?
How to separate strings with','
How to RDP with Fedora31
How to develop in Python
How to Delete with SQLAlchemy?
How to use fixture in Django to populate sample data associated with a user model
How to handle static files when deploying to production with Django
How to convert an array to a dictionary with Python [Application]
How to output a document in pdf format with Sphinx
Recommendations for django, wagtail ~ Why develop a website with python ~
How to check ORM behavior in one file with django
I want to make a blog editor with django admin