Posts By Nishu (33)

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

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

Pipenv Installation

What is Pipenv??

pipenv is a better package.

It contain pipfile.lock which contain all require package & dependencies

pipfile is automatically installed.

pipenv can work with requirement.txt file too. If there is one automatically detect it & convert into a pipfile.

Install Pipenv

Before installation get to know python is already installed

$python -V

$pip -V

$pip install pipenv or pipenv install --dev

$pipenv -h (to check the pipenv correctly installed)

$pipenv shell

$exit or deactivate

If showing pipenv not recognized as internal or external command , have to set Path in environment variable.

Error while cloning--- 'git' is not recognized as an internal or external command, operable program

Already installed in Linux--> No Need to do any process

Windows-->

1- Install Git -- https://git-scm.com/download/win

2-Set Path

Go to Start

Start typing 'This PC'

Right-click This PC, choose Properties

On the left side of the window that pops up, click on Advanced System Settings

Click on the Advanced tab

Click on the Environmental Variables button at the bottom

Down in the System Variables section, double-click Path

Click the New button in the top right corner

Add this path: C:\Program Files\Git\bin\ then click the enter key

Add another path: C:\Program Files\Git\cmd

Close & re-open the console if it's already open.

1 2 3 Next Last