Python Projects Rating 5 out of 5

Create an E-commerce Website with Django - Part 1

Create an E-commerce Website with Django - Part 1 Dec. 12, 2020

What is E-Commerce Website?

E-commerce Website refers to the buying and selling of goods or services using the internet, and the transfer of money and data to execute these transactions. 

Example: Amazon, Flipkart, Myntra, Paytm Mall etc...

 

Creating E-Commerce Website with Django

I hope all of you are familiar with Python and Django. If not then you can learn basics of Python and Django to get started.

Start a Django Project and App 

If you don't know how to start a Django project, learn from here

Save and run the following python script to create a django project automatically.

import os
import sys
import webbrowser


def launch(project, app):
    virtual = f'{project}-VE'
    setting = f'''


#Additional Required Setting
import os
INSTALLED_APPS+=["{app}"]
TEMPLATES[0]["DIRS"]=[os.path.join(BASE_DIR,"templates")]
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]

MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"'''



    urls = f'''
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('{app}.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)'''

    urls2 = f'''
from . import views
from django.urls import path
urlpatterns = [
    path('', views.index)
]
    '''
    views = '''
from django.shortcuts import render

def index(request):
    return render(request, 'index.html')
'''

    template = '''
<html>
<head>
    <title>Wecome to CODEVER</title>
</head>
<body>
    <h1>Thanks to learn from CODEVER<h1>
    <h2>Hope you enjoyed the tutorial. Don't forget to rate and comment.</h2>
</body>
</html>
    '''


    cd = os.getcwd()
    os.system('pip install virtualenv')
    os.system(f'virtualenv {virtual}')
    os.system('call virtual\Scripts\activate')
    os.chdir(virtual)
    os.system('pip install django')
    os.system(f'django-admin startproject {project}')
    os.chdir(project)
    os.system(f'django-admin startapp {app}')
    os.system('python manage.py migrate')
    os.system('python manage.py createsuperuser --username admin')
    os.chdir(os.path.join(cd,f'{virtual}/{project}'))
    os.mkdir(os.path.join(cd,f'{virtual}/{project}/templates'))
    os.mkdir(os.path.join(cd, f'{virtual}/{project}/static'))
    os.chdir(os.path.join(cd, f'{virtual}/{project}/{project}'))
    with open('settings.py', 'a+',encoding='utf-8') as f:
        f.write(setting)
    with open('urls.py','w',encoding='utf-8') as f:
        f.write(urls)
    os.chdir(f'../{app}')
    with open('urls.py', 'w+', encoding='utf-8') as f:
        f.write(urls2)
    with open('views.py', 'w+', encoding='utf-8') as f:
        f.write(views)
    os.chdir(os.path.join(cd, f'{virtual}/{project}/templates'))
    with open('index.html','w+',encoding='utf-8') as f:
        f.write(template)
    os.chdir('..')
    webbrowser.open('http://127.0.0.1:8000')
    os.system('python manage.py runserver')


project = str(input("Your Project Name: "))
app = str(input("Your App Name: "))
launch(project, app)

I have created a Django project named mycart and app named shop for tutorial.

Create a base template

Base template is common template or html code which is required in most of the pages. You can create it separately and use in any page. 

Example: Header and Footer are the same for every web page so we can write html for header and footer in base template.

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Mycart</title>
</head>
<style>
    footer{
        background: black;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 5rem;
        width: 100vw;
        color: white;
    }
</style>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">Mycart</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" 
data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" 
aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav mr-auto mb-2 mb-lg-0">
            <li class="nav-item">
              <a class="nav-link active" aria-current="page" href="#">Home</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Shop</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">About</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Category</a>
            </li>
          </ul>
          <form class="d-flex">
            <input class="form-control ml-2" type="search" placeholder="Search" aria-label="Search">
            <button class="btn btn-outline-light" type="submit">Search</button>
          </form>
        </div>
      </div>
    </nav>

    <div class=container>
     {%block main%}{%endblock%}
     </div>

    <footer>
        <div>Copyright <i class="fa fa-copyright" aria-hidden="true"></i> 2020 Codever, All Rights Reserved</div>
    </footer>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW"
        crossorigin="anonymous"></script>
</body>

</html>

I have created the base template with Bootstrap. 

{%block <block-name>%}{%endblock%} can be replaced in other template while using the base. 

To use the base template in another html code, Use {%extends '<filename.html>'%} at the starting of the new page.

Write your code inside {%block <block-name>%}{%endblock%}.

It will use the base file and instead of {%block <block-name>%}{%endblock%} , The html code inside this in main page will take place.

{% extends 'base.html'%}
{%block main%}
Landing Page or Index Page
{%endblock%}
    

Here I have used my base.html file in index.html file.

Similarly, Create another required pages such as shop, about, contact automatically by running the following python script and modify the html pages.

import webbrowser
import os 

html = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>This is your new HTML page. Change the file content in templates folder</h1>
</body>
</html>
'''

def createHTML(project, app, path, view=False):
    root = os.getcwd()
    if(view):
        urls=f'''+path({path},views.{path.capitalize}{view.capitalize}.as_view()
        '''
        with open(f'{root}/{project}-VE/{project}/{app}/views.py','a+',enccoding='utf-8') as f:
            if(f.read().index(f'from django.views.generic.{view}') == -1):
                f.seek(0)
                f.write(f'''
from django.views.generic.{view} import {view.capitalize()}View\n
                ''')
                f.seek(len(f.read()))
                f.write(f'''\n\n
class {path.capitalize}{view.capitalize}({view.capitalize()}View):
    template = '{path}.html'
                ''')
    else:
        urls = f'''
    path('{path}',views.{path}),
]
        '''
        views = f'''\n
def {path}(request):
    return render(request,'{path}.html')
        '''
        with open(f'{root}/{project}-VE/{project}/{app}/views.py', 'a+', encoding='utf-8') as f:
            f.write(views)
    os.system(f'call {project}-VE/Scripts/activate')
    os.chdir(os.path.join(root,f'{project}-VE/{project}/templates'))
    with open(f'{path}.html','w+',encoding='utf-8') as f:
        f.write(html)
    os.chdir(f'../{app}')
    with open('urls.py','r+',encoding='utf-8') as f:
        _ = f.read().replace(']',urls)
    with open('urls.py', 'w', encoding='utf-8') as f:
        f.write(_)
    os.chdir(os.path.join(root, f'{project}-VE/{project}'))
    webbrowser.open(f'http://127.0.0.1:8000/{path}')
    os.system('python manage.py runserver')



project = input('Project: ')
app = input('App: ')
page = input('Page: ')
createHTML(project, app, page)

In this tutorial, You have created the basic E-commerce templates. In next tutorial, You will create required models such as Profiles, Products and Reviews etc.

Don't forget to rate and comment.


Rate this post

Comments