Build an eCommerce site in Django: Part-2

V7: Django Form

Create forms.py inside ecommerce(src/ecommerce/forms.py)

from django import forms

class ContactForm(forms.Form):
    fullname = forms.CharField(widget=forms.TextInput(attrs={
        "class": "form-control",
        "placeholder": "Your fullname"
    }))
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={
        "class": "form-control",
        "placeholder": "Your email"
    }))
    content = forms.CharField(widget=forms.Textarea(
        attrs={
        "class": "form-control",
        "placeholder": "Your message"
    }))

    def clean_email(self):
        email = self.cleaned_data.get("email")
        if not "gmail.com" in email:
            raise forms.ValidationError("Email has to be gmail.com")
        return email

Update Views.py

from .forms import ContactForm

def contact_page(request):
    contact_form = ContactForm(request.POST or None)
    context = {
       "title" : "Hi!This is my Conatct Page",
        "content": "Conatct: XYZ",
        "form" : contact_form
    }
    if contact_form.is_valid():
        print(contact_form.cleaned_data)
    # if request.method == 'POST':
    #     # print(request.POST)
    #     print(request.POST.get('fullname'))
    #     print(request.POST.get('email'))
    #     print(request.POST.get('content'))
    return render(request, "contact/view.html", context)

Update views.html((src/templates/contact/view.html)

<div class="container">
    <div class="row">
      <div class="col">
      <p> {{ content }} </p>
        <div class="col-sm-6 col-12">
           <form method="POST"> {% csrf_token %}
             {{ form }}
             <button type="submit" class="btn btn-default">Submit</button>
      </form>
<!--      <form method="POST"> {% csrf_token %}-->
<!--        <input type="text" class="form-control" placeholder="Name" name="fullname">-->
<!--        <input type="email" class="form-control" placeholder="Email" name="email">-->
<!--        <textarea name="content" class="form-control" placeholder="Your Content"></textarea>-->
<!--        <button type="submit" class="btn btn-default">Submit</button>-->
<!--      </form>-->
          </div>
      </div>
    </div>
  </div>

V8: User Login

Update forms.py inside ecommerce(src/ecommerce/forms.py)

class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

update view.py

from django.shortcuts import render, redirect

from .forms import ContactForm, LoginForm

from django.contrib.auth import authenticate, login

def login_page(request):
    form = LoginForm(request.POST or None)
    context = {
        "form": form
    }
    print("User Logged In")
    # print(request.user.is_authenticated)
    if form.is_valid():
        print(form.cleaned_data)
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(request, username=username, password=password)
        print(user)
        if user is not None:
            # print(request.user.is_authenticated)
            login(request, user)
            context['form'] = LoginForm()
            return redirect("/login")
        else:
            print("Error")
    return render(request, "auth/login.html", context)

urls.py

from .views import home_page, about_page, contact_page, login_page

urlpatterns = [
    path('login/', login_page),

]
  • Create new directory(auth) inside the ecommerce(src/ecommerce/auth)
  • Create new login.html file inside the template(src/ecommerce/auth/login.html)

<< Part-1 Part-3 >>

View More...

Build an eCommerce site in Django: Part-1

V1: Virtual Environment

Make a Folder Project(ecommerce) and change directory

mkdir ecommerce
cd ecommerce

Virtual environment for window machine and activate

python -m virtualenv env
env\scripts\activate

Virtual environment for linux machine and activate

python -m venv env
source env/bin/activate

Deactivate virtual environment

(if you want to deactivate a virtual environment by typing “deactivate”)

V2: Start Project

Installed Django

pip install Django
mkdir src && cd src
django-admin startproject ecommerce .
Python manage.py runserver

Note: (space dot( .) created this folder inside the src folder not new project)

File Structure

  • Ecommerce
    • src
      • ecommerce
      • init.py
      • asgi.py
      • settings.py
      • urls.py
      • wsgi.py
    • dbsqlite3
    • manage.py

V-3: Render Html

Create New file views.py inside the src/ecommerce/views.py

from django.shortcuts import HttpResponse
from django.shortcuts import render

def home_page(request):
    return HttpResponse ("<h1>Hi Nishu</h1>")


def home_page_old(request):
    html = """<!doctype html>
                <html lang="en">
                <head>
                    <title>Hello, world!</title>
                </head>
                <body>
                    <h1>Hello, world!</h1>
                </body>
            </html>"""

    # return HttpResponse ("<h1>Hi Nishu</h1>")
    return HttpResponse (html)

urls.py

from django.contrib import admin
from django.urls import path
from .views import home_page

urlpatterns = [
                path('admin/', admin.site.urls),
                path('$/', home_page),
              ]

V4: Django Template

  • Create New Directory templates inside the src/templates/home_page.html
  • Copy & paste starter template from Bootstrap.com in home_page.html
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <title>Hello, Nishu!</title>
  </head>
  <body>
    <h1>Hello, Nishu!</h1>
    <!-- Optional JavaScript; choose one of the two! -->
    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
    -->
  </body>
</html>

Add templates direcory path(BASE_DIR/'templates') in settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR/'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': ['django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Add db direcory path for sqlite3 (BASE_DIR / 'db.sqlite3) in settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

V5: Template Context

  • Open views.py file in core directory and fill the views with this script code
from django.shortcuts import HttpResponse
from django.shortcuts import render

def home_page(request):
    context = {
       "title" : "Hi This is my home Page",
       "content" : "Welcome to our Scorpio World"
    }
    return render(request, "home_page.html", context)

def about_page(request):
    context = {
       "title" : "Hi This is my About Page",
        "content": "About Scorpio"
    }
    return render(request, "home_page.html", context)

def contact_page(request):
    context = {
       "title" : "Hi This is my Conatct Page",
        "content": "Conatct: 787888"
    }
    return render(request, "home_page.html", context

Managing Url and Templating

from django.contrib import admin
from django.urls import path
from .views import home_page, about_page, contact_page
urlpatterns = [
    path('admin/', admin.site.urls),
    path('$/', home_page),
    path('about/', home_page),
    path('contact/', contact_page),
]

Create home_page.html in templates directory(src/templates/home_page.html)

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <title>Hello, Nishu!</title>
  </head>
  <body>
  <div class="text-center">
   <h1>{{ title }}</h1>
  </div>
  <div class="container">
    <div class="row">
      <p> {{ content }} </p>
    </div>
  </div>
    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
    -->
  </body>
</html>

V6: HTML Form

  • Create New Directory(contact) inside the template(src/templates/contact)
  • Create New Html(view.html) file inside the template(src/templates/contact/view.html)
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <title>Hello, Nishu!</title>
  </head>
  <body>
  <div class="text-center">
   <h1>{{ title }}</h1>
   <h1>Scorpion's Site</h1>
  </div>
  <div class="container">
    <div class="row">
      <div class="col">
      <p> {{ content }} </p>
        <div class="col-sm-6 col-12">
      <form method="POST"> {% csrf_token %}
        <input type="text" class="form-control" placeholder="Name" name="fullname">
        <input type="email" class="form-control" placeholder="Email" name="email">
        <textarea name="content" class="form-control" placeholder="Your Content"></textarea>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
          </div>
      </div>
    </div>
  </div>
    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
    -->
  </body>
</html>

Update Views.py

def contact_page(request):
    context = {
       "title" : "Hi!This is my Conatct Page",
        "content": "Conatct: XYZ"
    }
    if request.method == 'POST':
        # print(request.POST)
        print(request.POST.get('fullname'))
        print(request.POST.get('email'))
        print(request.POST.get('content'))
    return render(request, "contact/view.html", context)

Part-2 >>

View More...

How can make join with django orm?

categroy_filter = CategoryFilter.objects.values('filter__filter_id', 'filter__filter_title').filter(
category_id=1,
filter__filter_title="xxxxx")
get_first_filter_id = categroy_filter[0:1][0]['filter__filter_id']
View More...

How Can Upload Files/Images using Django Form

# Create your views here.

def html_view(request):

   if request.method == 'GET':

       return render(request, "form.html")

dd = request.FILES['image_url']

 dd2 = request.FILES['image_url2']

 dd3 = request.FILES['image_url3']

 dd4 = request.FILES['image_url4']

 images = [dd, dd2, dd3, dd4]

 for image in images:

   ProductImage.objects.create('product'=request.POST['product'], 'image_url': image)

return render(request, "form.html")

View More...

Django Python Command

Verify Python Installation

>python

Check Python Version

>python --version

shortcut command

>python -V

>python3 -V

Check if PIP is Already Installed

>pip help

Installing PIP On Windows Machine

Download PIP get-pip.py

Copy PIP code and save file name is get-pip.py

PIP is a command-line program. When you install PIP, the PIP command is added to your system.

>python  get-pip.py

Check PIP Version

>pip --version

shortcut command

>pip -V

Upgrading PIP for Python on Windows Machine

>python -m pip install --upgrade pip

Downgrade PIP Version

>python -m pip install pip==18.1

Creating virtual environment for window Machine

>python -m virtualenv env

Activate virtual environment for window Machine

>env\scripts\activate

Create Virtual environment for ubuntu/linux machine

>python -m venv env

Activate virtual environment for ubuntu/linux machine

>source env/bin/activate

Deactivate virtual environment

>deactivate

Install django and mysqlclient sh > pip install django > pip install mysqlclient

Install Django

>python -m pip install django

shortcut command

>pip install django

If you wante to install Specific version of django

>pip install django==3.1.7

Check Django Version

>django-admin --version

Install mysqlclient for MYSQL Database

>pip install mysqlclient

if you got installation error in window 

 then download whl files from here

Download :  https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient

for window 32 bit

>pip install mysqlclient-1.4.6-cp38-cp38-win32.whl

for window 64 bit

>pip install mysqlclient-1.4.6-cp38-cp38-win_amd64.whl

Creating Django Project

>django-admin startproject demo_project

Creating Django APP

>django-admin startapp demo_app

Note: django-admin is equal to python manage.py command

i.e django-admin = python manage.py

>python manage.py startapp demo_app

Django Migration Command

>python manage.py makemigrations

>python manage.py migrate

Create Super User for Django admin

>python manage.py createsuperuser

Run Server for Django Project

>python manage.py runserver

Exporting data from a Django project

>python manage.py dumpdata > vishavjeet_data.json

If you want the exported file to have a readable JSON,

 then you can use "--indent".

>python manage.py dumpdata --indent=4 > dumped_data.json

Importing data from a Django project

>python manage.py loaddata < vishavjeet_data.json

View More...

1 2 Next Last