0% found this document useful (0 votes)
39 views138 pages

FinalTravel Diary

The document outlines the development of a Django-based web application called 'Travel Diary' that allows users to document and share their travel experiences. It discusses the strengths of Python and Django in web development, including their ease of use, extensive libraries, and built-in security features. Additionally, it provides a step-by-step guide for setting up a Django project, creating views, and defining models for the application.

Uploaded by

Divy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views138 pages

FinalTravel Diary

The document outlines the development of a Django-based web application called 'Travel Diary' that allows users to document and share their travel experiences. It discusses the strengths of Python and Django in web development, including their ease of use, extensive libraries, and built-in security features. Additionally, it provides a step-by-step guide for setting up a Django project, creating views, and defining models for the application.

Uploaded by

Divy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 138

Python with django

Project Profile
Title: Travel Diary
Abstract: "Travel Diary" is a Django-based web application designed to
help users document and share their favorite travel experiences. Users
can create personalized entries for each destination they visit, complete
with text descriptions and images. With a user-friendly interface and
robust backend functionality, Travel Diary provides a seamless platform
for users to capture and cherish their travel memories while inspiring
others with their experiences. With its responsive design and interactive
map integration, users can visually track their journeys and inspire others
to embark on their own adventures.
Key-Words: Diary, Travel, Place, Memories
Modules: Admin, User
Technology:
Front-End - HTML, CSS, JavaScript, Bootstrap
Back End - Django web framework (Python)
Database – SQLite

1
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 1

“Analyzing the Powers of Python and Django”

Prompt: Create a brief analysis outlining Python's strengths in conjunction


with the Django framework.

Python and Django synergize to offer a formidable toolkit for web development.
Python's versatility lies in its simplicity and readability, making it an ideal language
for beginners and seasoned developers alike. Its extensive libraries and
frameworks cater to a wide range of applications, from web development to data
science and machine learning. Python's dynamic typing and interpreted nature
streamline the development process, allowing for rapid prototyping and iterative
development cycles.

Django, on the other hand, is a high-level web framework built on top of Python,
designed to facilitate the development of complex, database-driven websites. Its
"batteries-included" philosophy provides developers with a robust set of tools
right out of the box, including an ORM (Object-Relational Mapping) layer, a built-
in admin interface, and a powerful URL routing system. Django's emphasis on DRY
(Don't Repeat Yourself) principles and convention over configuration minimizes
boilerplate code and encourages best practices, resulting in cleaner and more
maintainable codebases.

Together, Python and Django empower developers to build scalable and


maintainable web applications with ease. Python's rich ecosystem and expansive
community support complement Django's batteries-included approach, providing
developers with a comprehensive solution for web development. Whether
building a simple blog or a complex e-commerce platform, Python and Django
offer the flexibility and tools necessary to bring ideas to life efficiently.

2
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Furthermore, Python's clean and expressive syntax enhances developer


productivity, allowing for faster development cycles and reduced time to market.
Django's built-in security features, such as protection against common web
vulnerabilities like SQL injection and CSRF (Cross-Site Request Forgery), bolster
the security of web applications, giving developers peace of mind when deploying
their projects to production environments.

In conclusion, the powers of Python and Django lie in their symbiotic relationship,
where Python's simplicity and versatility complement Django's robustness and
scalability. Together, they form a formidable duo that empowers developers to
build web applications that are both powerful and maintainable, catering to a
wide range of use cases and industries.

3
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Prompt: Compare python growth with other programming languages

4
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 2

“Web application utilizing Django”

Prompt: Development of a Django project with code.

1. **Install Python**: First, ensure you have Python installed on your system. You can
download and install it from the [official Python website] (https://www.python.org/). Django
requires Python 3.6 or higher.

2. **Install Django**: You can install Django using pip, Python's package manager. Open your
command line or terminal and run the following command:
```
pip install django
‘’’
3. **Create a Django Project**: Once Django is installed, you can create a new Django project
using the `django-admin` command-line tool. Navigate to the directory where you want to
create your project and run:
```
Django-admin startproject projectname
‘’’
Replace `projectname` with the name you want for your project.
4. **Navigate to Your Project Directory**: After creating the project, navigate into the project
directory:
```
Cd projectname
‘’’

5
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

5. **Run the Development Server**: You can start the Django development server to see your
project in action. Run the following command:
```
Python manage.py runserver
‘’’
6. **Check Your Project**: Once the development server is running, open a web browser and
go to `http://127.0.0.1:8000/` (or `http://localhost:8000/`). You should see the Django
welcome page, indicating that your project is set up correctly.

7. **Create Django Apps**: In Django, functionality is organized into apps. You can create a
new app within your project using the following command:
```
Python manage.py startapp appname
‘’’
Replace `appname` with the name you want for your app.

8. **Configure Your Project**: You can configure your project settings in the `settings.py` file
within your project directory. This includes database configuration, static files, middleware, and
more.

9. **Define URLs and Views**: Define URL patterns in the `urls.py` file within your project and
app directories, and define corresponding views to handle those URLs.

10. **Create Models**: Define your data models in the `models.py` file within your app
directory using Django's ORM (Object-Relational Mapping).

6
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

11. **Run Migrations**: After defining your models, you need to create database tables for
them. Run the following command to apply migrations:
```
Python manage.py makemigrations
Python manage.py makemigrate
‘’’

12. **Create Superuser**: If you need to access the Django admin interface, create a superuser
account using the following command:
```
Python manage.py createsuperuser
‘’’

That's it! You've set up a Django project and are ready to start building your web application.
Remember to consult the [Django documentation] (https://docs.djangoproject.com/en/stable/)
for more detailed information on any of these steps.

7
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 3

“Index View”

Prompt: Creating view for index

Step 1: Go to ‘views.py’ location and write code.

from django.shortcuts import render,redirect


from .models import Memory
from .form import MemForm
#from django.http import HttpResponse

def index_view(request,*args,**kwargs):
mem=Memory.objects.all()
cont={
"obj":mem
}

return render(request,'index.html',cont)
#return redirect('home/')
def home_view(request):
return render(request,'index.html')

8
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Step 2: ‘urls.py’ is a Python module where you define the URL patterns for your web
application. It acts as a router that maps URLs to views. When a user makes a request to your
Django application, Django uses the urls.py file to determine which view should handle the
request.

from django.urls import path


from .views import index_view,home_view,add_view,desc_view
from django.conf import settings
from django.conf.urls.static import static
app_name="memory"
urlpatterns=[
path('index/',index_view,name='index'),
path('home/',home_view,name='home'),
path('add/',add_view,name='add'),
path('work/<int:id>',desc_view,name='desc'),
]+ static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)

9
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 4

“Memories”

Prompt: Travel Memories Details

Step 1: Go to ‘forms.py’ location and write code for Memory Form.

from django import forms


from django.forms import ModelForm,TextInput
from .models import Memory

class MemForm(forms.Form):
image = forms.ImageField()
class Meta:
model=Memory
exclude = ['title','place','desc']
#fields=['image']
#widgets={'name':TextInput(attrs={'class':'input','placeholder':'City Name'})}

Step 2: Go to ‘models.py’ location and build model for Memories.

from django.db import models


from django.conf import settings
from django.conf.urls.static import static
from django.urls import reverse

# Create your models here.


class Memory(models.Model):
#print(settings.STATIC_URL)
title= models.CharField(max_length=25,null=True,blank=True)
place=models.CharField(max_length=20,null=True,blank=True)
desc=models.TextField(default='write here',null=True,blank=True)
10
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

image=models.ImageField(null=True,blank=True,upload_to='static/assets/img/')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("memory:desc",kwargs={"id":self.id})

Step 3: Migrate Models, after defining models, run the `makemigrations` and `migrate`
commands to create corresponding database tables based on the model definitions.

python manage.py makemigrations


python manage.py migrate

11
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 5

“Landing Page”

Prompt: Getting Website home

Step 1: Create ‘index.html’

<html lang="en">

<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">

<title>Echo of the journey</title>


<meta content="" name="descriptison">
<meta content="" name="keywords">
{% load static %}

<!-- Favicons -->


<link href="{% static 'img/favicon.png' %}" rel="icon">
<link href="{% static 'assets/img/apple-touch-icon.png' %}" rel="apple-touch-icon">

<!-- Google Fonts -->


<link href="https://fonts.googleapis.com/css?family=https://fonts.googleapis.com/css?
family=Inconsolata:400,500,600,700|Raleway:400,400i,500,500i,600,600i,700,700i"
rel="stylesheet">

<!-- Vendor CSS Files -->


<link href='{% static "assets/vendor/bootstrap/css/bootstrap.min.css" %}' rel="stylesheet"
type="text/css">
<link href="{% static 'assets/vendor/icofont/icofont.min.css' %}" rel="stylesheet"
type="text/css">
<link href="{% static 'assets/vendor/aos/aos.css' %}" rel="stylesheet">
<link href="{% static 'assets/vendor/line-awesome/css/line-awesome.min.css'%}"
12
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

rel="stylesheet">
<link href="{% static 'assets/vendor/owl.carousel/assets/owl.carousel.min.css'%}"
rel="stylesheet">

<!-- Template Main CSS File -->


<link href="{% static 'assets/css/style.css'%}" rel="stylesheet">

<!-- =======================================================
* Template Name: MyPortfolio - v2.0.0
* Template URL: https://bootstrapmade.com/myportfolio-bootstrap-portfolio-website-
template/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
======================================================== -->
</head>

<body>

<!-- ======= Navbar ======= -->


<div class="collapse navbar-collapse custom-navmenu" id="main-navbar">
<div class="container py-2 py-md-5">
<div class="row align-items-start">
<div class="col-md-2">
<ul class="custom-menu">
<li class="active"><a href="{% url 'memory:index'%}">Home</a></li>
<li><a href="{% url 'memory:add'%}">New memory</a></li>
</ul>
</div>
<div class="col-md-6 d-none d-md-block mr-auto">
<div class="tweet d-flex">

<div>
<p>LIKE ALL GREAT TRAVELLERS, I HAVE SEEN MORE THAN I REMEMBER AND
REMEMBER MORE THAN I HAVE SEEN</p>
</div>
</div>
</div>
<div class="col-md-4 d-none d-md-block">
<h3>Memories</h3>
<p>Every journey is a beautiful memory. </p>
</div>
</div>

13
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

</div>
</div>

<nav class="navbar navbar-light custom-navbar">


<div class="container">
<a class="navbar-brand" href="{% url 'memory:index'%}">Echo of my Journey </a>

<a href="#" class="burger" data-toggle="collapse" data-target="#main-navbar">


<span></span>
</a>

</div>
</nav>

<main id="main">

<!-- ======= Works Section ======= -->


<section class="section site-portfolio">
<div class="container">
<div class="row mb-5 align-items-center">
<div class="col-md-12 col-lg-6 mb-4 mb-lg-0" data-aos="fade-up">
<h2>Cherished moments of my voyage</h2>
<p class="mb-0">Your name </p>
</div>
<div class="col-md-12 col-lg-6 text-left text-lg-right" data-aos="fade-up" data-aos-
delay="100">
<div id="filters" class="filters">

</div>
</div>
</div>

<div id="portfolio-grid" class="row no-gutter" data-aos="fade-up" data-aos-


delay="200">
{%for mem in obj %}
<div class="item web col-sm-6 col-md-4 col-lg-4 mb-4">
<a href='{{ mem.get_absolute_url }}' class="item-wrap fancybox">
<div class="work-info">
<h3>{{mem.title}}</h3>
<span>{{mem.place}}</span>

</div>
<img class="img-fluid" src="{{ STATIC_URL }}/{{ mem.image }}" alt="image">
</a>
14
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

</div>
{% endfor %}

</div>
</div>
</section><!-- End Works Section -->

</main><!-- End #main -->

<!-- ======= Footer ======= -->


<footer class="footer" role="contentinfo">
<div class="container">
<div class="row">
<div class="col-sm-6">
<p class="mb-1">&copy; Copyright MyPortfolio. All Rights Reserved</p>
<div class="credits">
<!--
All the links in the footer should remain intact.
You can delete the links only if you purchased the pro version.
Licensing information: https://bootstrapmade.com/license/
Purchase the pro version with working PHP/AJAX contact form:
https://bootstrapmade.com/buy/?theme=MyPortfolio
-->
Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a>
</div>
</div>

</div>
</div>
</footer>

<a href="#" class="back-to-top"><i class="icofont-simple-up"></i></a>

<!-- Vendor JS Files -->


<script src="{% static 'assets/vendor/jquery/jquery.min.js' %}"></script>
<script src="{% static 'assets/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
<script src="{% static 'assets/vendor/jquery.easing/jquery.easing.min.js' %}"></script>
<script src="{% static 'assets/vendor/php-email-form/validate.js' %}"></script>
15
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<script src="{% static 'assets/vendor/aos/aos.js' %}"></script>


<script src="{% static 'assets/vendor/isotope-layout/isotope.pkgd.min.js' %}"></script>
<script src="{% static 'assets/vendor/owl.carousel/owl.carousel.min.js' %}"></script>

<!-- Template Main JS File -->


<script src="{% static 'assets/js/main.js' %}"></script>

</body>

</html>

16
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 6

“Create Your Memories”

Prompt: Add Various Memories

Step 1: Go to ‘views.py’ location and write code.

def add_view(request):
mem=Memory()
#new_city=form.cleaned_data['title']
#print("Vail",form)
if request.method=='POST':
mem.title= request.POST.get('name')
mem.place= request.POST.get('subject')
mem.desc= request.POST.get('message')

form=MemForm(request.POST ,request.FILES)

if form.is_valid():
mem.image=form.cleaned_data["image"]
mem.save()

form=MemForm(request.POST,request.FILES)
context={
'form':form
}

print(request.POST,request.FILES)
return render(request,'contact.html',{})

17
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 7

“Contact Me”

Prompt: Contact Info

Step 1: Create templates for contact.

<!—contact.html -->

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

<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
{% load static %}
<title>Add new memory</title>
<meta content="" name="descriptison">
<meta content="" name="keywords">

<!-- Favicons -->


<link href="{% static 'assets/img/favicon.png' %}" rel="icon">
<link href="{% static 'assets/img/apple-touch-icon.png' %}" rel="apple-touch-icon">

<!-- Google Fonts -->


<link href="https://fonts.googleapis.com/css?family=https://fonts.googleapis.com/css?
family=Inconsolata:400,500,600,700|Raleway:400,400i,500,500i,600,600i,700,700i"
rel="stylesheet">

<!-- Vendor CSS Files -->


<link href="{% static 'assets/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'assets/vendor/icofont/icofont.min.css' %}" rel="stylesheet">
<link href="{% static 'assets/vendor/aos/aos.css' %}" rel="stylesheet">
<link href="{% static 'assets/vendor/line-awesome/css/line-awesome.min.css' %}"
rel="stylesheet">
<link href="{% static 'assets/vendor/owl.carousel/assets/owl.carousel.min.css' %}"

18
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

rel="stylesheet">

<!-- Template Main CSS File -->


<link href="{% static 'assets/css/style.css' %}" rel="stylesheet">

<!-- =======================================================
* Template Name: MyPortfolio - v2.0.0
* Template URL: https://bootstrapmade.com/myportfolio-bootstrap-portfolio-website-
template/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
======================================================== -->
</head>

<body>

<!-- ======= Navbar ======= -->


<div class="collapse navbar-collapse custom-navmenu" id="main-navbar">
<div class="container py-2 py-md-5">
<div class="row align-items-start">
<div class="col-md-2">
<ul class="custom-menu">
<li class="active"><a href="{% url 'memory:index'%}">Home</a></li>
<li><a href="{% url 'memory:add'%}">New memory</a></li>
</ul>
</div>
<div class="col-md-6 d-none d-md-block mr-auto">
<div class="tweet d-flex">

<div>
<p>LIKE ALL GREAT TRAVELLERS, I HAVE SEEN MORE THAN I REMEMBER AND
REMEMBER MORE THAN I HAVE SEEN</p>
</div>
</div>
</div>
<div class="col-md-4 d-none d-md-block">
<h3>Memories</h3>
<p>Every journey is a beautiful memory. </p>
</div>
</div>

</div>
</div>

19
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<nav class="navbar navbar-light custom-navbar">


<div class="container">
<a class="navbar-brand" href="{% url 'memory:index'%}">Echo of my journey</a>

<a href="#" class="burger" data-toggle="collapse" data-target="#main-navbar">


<span></span>
</a>

</div>
</nav>

<main id="main">

<section class="section pb-5">


<div class="container">

<div class="row mb-5 align-items-end">


<div class="col-md-6" data-aos="fade-up">
<h2>Add new memory</h2>
<p class="mb-0">Add a new image and description
</p>
</div>

</div>

<div class="row">
<div class="col-md-6 mb-5 mb-md-0" data-aos="fade-up">

<form action="{% url 'memory:add'%}" method="post" enctype= multipart/form-


data>{% csrf_token %}

<div class="row">
<div class="col-md-6 form-group">
<label for="name">Title</label>

<input type="text" name="name" class="form-control" id="name" data-


rule="minlen:4" data-msg="Please enter at least 4 chars" />

</div>
<br>
<div class="col-md-12 form-group">
<label for="name">Place of memory</label>
<input type="text" class="form-control" name="subject" id="subject" data-
20
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />


<div class="validate"></div>
</div>
<br>
<div class="col-md-12 form-group">

<label for="img">Select image:</label><br>


<input id="id_image" type="file" class="" name="image">
<div class="validate"></div>
</div>
<br>
<div class="col-md-12 form-group">
<label for="name">Description</label>
<textarea class="form-control" name="message" cols="30" rows="20" data-
rule="required" data-msg="Please write something for us"></textarea>
<div class="validate"></div>
</div>

<div class="col-md-6 form-group">


<input type="submit" class="readmore d-block w-100" value="Submit">
</div>
</div>

</form>

</div>

</div>

</div>

</section>

</main><!-- End #main -->

<!-- ======= Footer ======= -->


<footer class="footer" role="contentinfo">
<div class="container">
<div class="row">
<div class="col-sm-6">
<p class="mb-1">&copy; Copyright MyPortfolio. All Rights Reserved</p>
21
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<div class="credits">
<!--
All the links in the footer should remain intact.
You can delete the links only if you purchased the pro version.
Licensing information: https://bootstrapmade.com/license/
Purchase the pro version with working PHP/AJAX contact form:
https://bootstrapmade.com/buy/?theme=MyPortfolio
-->
Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a>
</div>
</div>

</div>
</div>
</footer>

<a href="#" class="back-to-top"><i class="icofont-simple-up"></i></a>

<!-- Vendor JS Files -->


<script src="{% static 'assets/vendor/jquery/jquery.min.js' %}"></script>
<script src="{% static 'assets/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
<script src="{% static 'assets/vendor/jquery.easing/jquery.easing.min.js' %}"></script>
<script src="{% static 'assets/vendor/php-email-form/validate.js' %}"></script>
<script src="{% static 'assets/vendor/aos/aos.js' %}"></script>
<script src="{% static 'assets/vendor/isotope-layout/isotope.pkgd.min.js' %}"></script>
<script src="{% static 'assets/vendor/owl.carousel/owl.carousel.min.js' %}"></script>

<!-- Template Main JS File -->


<script src="{% static 'assets/js/main.js' %}"></script>

</body>

</html>

22
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 8

“Create Work”

Prompt: Add about works

Step 1: Create template “work-single.html”.

<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">

<title>Echo of the journey</title>


<meta content="" name="descriptison">
<meta content="" name="keywords">

<!-- Favicons -->


<link href="{% static 'assets/img/favicon.png' %}" rel="icon">
<link href="{% static 'assets/img/apple-touch-icon.png' %}" rel="apple-touch-icon">

<!-- Google Fonts -->


<link href="https://fonts.googleapis.com/css?family=https://fonts.googleapis.com/css?
family=Inconsolata:400,500,600,700|Raleway:400,400i,500,500i,600,600i,700,700i"
rel="stylesheet">

<!-- Vendor CSS Files -->


<link href="{% static 'assets/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'assets/vendor/icofont/icofont.min.css' %}" rel="stylesheet">
<link href="{% static 'assets/vendor/aos/aos.css' %}" rel="stylesheet">
<link href="{% static 'assets/vendor/line-awesome/css/line-awesome.min.css' %}"
rel="stylesheet">
<link href="{% static 'assets/vendor/owl.carousel/assets/owl.carousel.min.css' %}"
rel="stylesheet">

23
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<!-- Template Main CSS File -->


<link href="{% static 'assets/css/style.css' %}" rel="stylesheet">

<!-- =======================================================
* Template Name: MyPortfolio - v2.0.0
* Template URL: https://bootstrapmade.com/myportfolio-bootstrap-portfolio-website-
template/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
======================================================== -->
</head>

<body>

<!-- ======= Navbar ======= -->


<div class="collapse navbar-collapse custom-navmenu" id="main-navbar">
<div class="container py-2 py-md-5">
<div class="row align-items-start">
<div class="col-md-2">
<ul class="custom-menu">
<li class="active"><a href="{% url 'memory:index'%}">Home</a></li>
<li><a href="{% url 'memory:add'%}">New memory</a></li>
</ul>
</div>
<div class="col-md-6 d-none d-md-block mr-auto">
<div class="tweet d-flex">

<div>
<p>LIKE ALL GREAT TRAVELLERS, I HAVE SEEN MORE THAN I REMEMBER AND
REMEMBER MORE THAN I HAVE SEEN</p>
</div>
</div>
</div>
<div class="col-md-4 d-none d-md-block">
<h3>Memories</h3>
<p>Every journey is a beautiful memory. </p>
</div>
</div>

</div>
</div>

<nav class="navbar navbar-light custom-navbar">

24
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<div class="container">
<a class="navbar-brand" href="{% url 'memory:index'%}">Echo of my Journey</a>

<a href="#" class="burger" data-toggle="collapse" data-target="#main-navbar">


<span></span>
</a>

</div>
</nav>

<main id="main">

<section class="section">
<div class="container">
<div class="row mb-4 align-items-center">
<div class="col-md-6" data-aos="fade-up">
<h2>{{obj.title}}</h2>

<p>{{obj.place}}</p>
</div>
</div>
</div>

<div class="site-section pb-0">


<div class="container">
<div class="row align-items-stretch">
<div class="col-md-8" data-aos="fade-up">
<img src="{{ STATIC_URL }}/{{ obj.image }}" alt="Image" class="img-fluid">
</div>
<div class="col-md-3 ml-auto" data-aos="fade-up" data-aos-delay="100">
<div class="sticky-content">

<div class="mb-5">
<p>
{{obj.desc}}
</p>

</div>

</div>
</div>
</div>
</div>
25
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

</section>

</main><!-- End #main -->

<!-- ======= Footer ======= -->


<footer class="footer" role="contentinfo">
<div class="container">
<div class="row">
<div class="col-sm-6">
<p class="mb-1">&copy; Copyright MyPortfolio. All Rights Reserved</p>
<div class="credits">
<!--
All the links in the footer should remain intact.
You can delete the links only if you purchased the pro version.
Licensing information: https://bootstrapmade.com/license/
Purchase the pro version with working PHP/AJAX contact form:
https://bootstrapmade.com/buy/?theme=MyPortfolio
-->
Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a>
</div>
</div>
<div class="col-sm-6 social text-md-right">
<a href="#"><span class="icofont-twitter"></span></a>
<a href="#"><span class="icofont-facebook"></span></a>
<a href="#"><span class="icofont-dribbble"></span></a>
<a href="#"><span class="icofont-behance"></span></a>
</div>
</div>
</div>
</footer>

<a href="#" class="back-to-top"><i class="icofont-simple-up"></i></a>

<!-- Vendor JS Files -->


<script src="{% static 'assets/vendor/jquery/jquery.min.js' %}"></script>
<script src="{% static 'assets/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
<script src="{% static 'assets/vendor/jquery.easing/jquery.easing.min.js' %}"></script>
<script src="{% static 'assets/vendor/php-email-form/validate.js' %}"></script>
<script src="{% static 'assets/vendor/aos/aos.js' %}"></script>
<script src="{% static 'assets/vendor/isotope-layout/isotope.pkgd.min.js' %}"></script>
<script src="{% static 'assets/vendor/owl.carousel/owl.carousel.min.js' %}"></script>

26
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<!-- Template Main JS File -->


<script src="{% static 'assets/js/main.js' %}"></script>

</body>

</html>

27
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 9

“Work View”

Prompt: Creating View for single work

Step 1: Go to ‘views.py’ location and write code.

def desc_view(request,id):
m=Memory.objects.get(id=id)
cont={
"obj":m
}
return render(request,'work-single.html', cont)

28
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 10

“All Works”

Prompt: Get info on all works

Step 1: Create ‘works.html’

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

<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">

<title>MyPortfolio Bootstrap Template - Works</title>


<meta content="" name="descriptison">
<meta content="" name="keywords">

<!-- Favicons -->


<link href="assets/img/favicon.png" rel="icon">
<link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">

<!-- Google Fonts -->


<link href="https://fonts.googleapis.com/css?family=https://fonts.googleapis.com/css?
family=Inconsolata:400,500,600,700|Raleway:400,400i,500,500i,600,600i,700,700i"
rel="stylesheet">

<!-- Vendor CSS Files -->


<link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/vendor/icofont/icofont.min.css" rel="stylesheet">
<link href="assets/vendor/aos/aos.css" rel="stylesheet">
<link href="assets/vendor/line-awesome/css/line-awesome.min.css" rel="stylesheet">
<link href="assets/vendor/owl.carousel/assets/owl.carousel.min.css" rel="stylesheet">

<!-- Template Main CSS File -->

29
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<link href="assets/css/style.css" rel="stylesheet">

<!-- =======================================================
* Template Name: MyPortfolio - v2.0.0
* Template URL: https://bootstrapmade.com/myportfolio-bootstrap-portfolio-website-
template/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
======================================================== -->
</head>

<body>

<!-- ======= Navbar ======= -->


<div class="collapse navbar-collapse custom-navmenu" id="main-navbar">
<div class="container py-2 py-md-5">
<div class="row align-items-start">
<div class="col-md-2">
<ul class="custom-menu">
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About Me</a></li>
<li><a href="services.html">Services</a></li>
<li class="active"><a href="works.html">Works</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
<div class="col-md-6 d-none d-md-block mr-auto">
<div class="tweet d-flex">
<span class="icofont-twitter text-white mt-2 mr-3"></span>
<div>
<p><em>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam
necessitatibus incidunt ut officiis explicabo inventore. <br> <a
href="#">t.co/v82jsk</a></em></p>
</div>
</div>
</div>
<div class="col-md-4 d-none d-md-block">
<h3>Hire Me</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam necessitatibus
incidunt ut officiisexplicabo inventore. <br> <a href="#">[email protected]</a></p>
</div>
</div>

30
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

</div>
</div>

<nav class="navbar navbar-light custom-navbar">


<div class="container">
<a class="navbar-brand" href="index.html">MyPortfolio.</a>

<a href="#" class="burger" data-toggle="collapse" data-target="#main-navbar">


<span></span>
</a>

</div>
</nav>

<main id="main">

<!-- ======= Works Section ======= -->


<section class="section site-portfolio">
<div class="container">
<div class="row mb-5 align-items-center">
<div class="col-md-12 col-lg-6 mb-4 mb-lg-0" data-aos="fade-up">
<h2>Hey, I'm Johan Stanworth</h2>
<p class="mb-0">Freelance Creative &amp; Professional Graphics Designer</p>
</div>
<div class="col-md-12 col-lg-6 text-left text-lg-right" data-aos="fade-up" data-aos-
delay="100">
<div id="filters" class="filters">
<a href="#" data-filter="*" class="active">All</a>
<a href="#" data-filter=".web">Web</a>
<a href="#" data-filter=".design">Design</a>
<a href="#" data-filter=".branding">Branding</a>
<a href="#" data-filter=".photography">Photography</a>
</div>
</div>
</div>
<div id="portfolio-grid" class="row no-gutter" data-aos="fade-up" data-aos-
delay="200">
<div class="item web col-sm-6 col-md-4 col-lg-4 mb-4">
<a href="work-single.html" class="item-wrap fancybox">
<div class="work-info">
<h3>Boxed Water</h3>
<span>Web</span>
</div>

31
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<img class="img-fluid" src="assets/img/img_1.jpg">


</a>
</div>
<div class="item photography col-sm-6 col-md-4 col-lg-4 mb-4">
<a href="work-single.html" class="item-wrap fancybox">
<div class="work-info">
<h3>Build Indoo</h3>
<span>Photography</span>
</div>
<img class="img-fluid" src="assets/img/img_2.jpg">
</a>
</div>
<div class="item branding col-sm-6 col-md-4 col-lg-4 mb-4">
<a href="work-single.html" class="item-wrap fancybox">
<div class="work-info">
<h3>Cocooil</h3>
<span>Branding</span>
</div>
<img class="img-fluid" src="assets/img/img_3.jpg">
</a>
</div>
<div class="item design col-sm-6 col-md-4 col-lg-4 mb-4">
<a href="work-single.html" class="item-wrap fancybox">
<div class="work-info">
<h3>Nike Shoe</h3>
<span>Design</span>
</div>
<img class="img-fluid" src="assets/img/img_4.jpg">
</a>
</div>
<div class="item photography col-sm-6 col-md-4 col-lg-4 mb-4">
<a href="work-single.html" class="item-wrap fancybox">
<div class="work-info">
<h3>Kitchen Sink</h3>
<span>Photography</span>
</div>
<img class="img-fluid" src="assets/img/img_5.jpg">
</a>
</div>
<div class="item branding col-sm-6 col-md-4 col-lg-4 mb-4">
<a href="work-single.html" class="item-wrap fancybox">
<div class="work-info">
<h3>Amazon</h3>

32
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<span>brandingn</span>
</div>
<img class="img-fluid" src="assets/img/img_6.jpg">
</a>
</div>
</div>
</div>
</section><!-- End Works Section -->

<!-- ======= Testimonials Section ======= -->


<section class="section pt-0">
<div class="container">

<div class="owl-carousel testimonial-carousel">

<div class="testimonial-wrap">
<div class="testimonial">
<img src="assets/img/person_1.jpg" alt="Image" class="img-fluid">
<blockquote>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam necessitatibus
incidunt ut officiis
explicabo inventore.</p>
</blockquote>
<p>&mdash; Jean Hicks</p>
</div>
</div>

<div class="testimonial-wrap">
<div class="testimonial">
<img src="assets/img/person_2.jpg" alt="Image" class="img-fluid">
<blockquote>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam necessitatibus
incidunt ut officiis
explicabo inventore.</p>
</blockquote>
<p>&mdash; Chris Stanworth</p>
</div>
</div>

</div>

</div>
</section><!-- End Testimonials Section -->

33
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

</main><!-- End #main -->

<!-- ======= Footer ======= -->


<footer class="footer" role="contentinfo">
<div class="container">
<div class="row">
<div class="col-sm-6">
<p class="mb-1">&copy; Copyright MyPortfolio. All Rights Reserved</p>
<div class="credits">
<!--
All the links in the footer should remain intact.
You can delete the links only if you purchased the pro version.
Licensing information: https://bootstrapmade.com/license/
Purchase the pro version with working PHP/AJAX contact form:
https://bootstrapmade.com/buy/?theme=MyPortfolio
-->
Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a>
</div>
</div>
<div class="col-sm-6 social text-md-right">
<a href="#"><span class="icofont-twitter"></span></a>
<a href="#"><span class="icofont-facebook"></span></a>
<a href="#"><span class="icofont-dribbble"></span></a>
<a href="#"><span class="icofont-behance"></span></a>
</div>
</div>
</div>
</footer>

<a href="#" class="back-to-top"><i class="icofont-simple-up"></i></a>

<!-- Vendor JS Files -->


<script src="assets/vendor/jquery/jquery.min.js"></script>
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/jquery.easing/jquery.easing.min.js"></script>
<script src="assets/vendor/php-email-form/validate.js"></script>
<script src="assets/vendor/aos/aos.js"></script>
<script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
<script src="assets/vendor/owl.carousel/owl.carousel.min.js"></script>

<!-- Template Main JS File -->


<script src="assets/js/main.js"></script>

34
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

</body>

</html>

35
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 11
“QuerySet in Django framework”

Object-Relational Mapping (ORM) is an integral part of the framework, enabling developers to


interact with databases using Python objects. Django's ORM abstracts away the complexity of
SQL queries, allowing developers to focus on application logic rather than database operations
directly. Here's an overview of how ORM queries work in Django:

1. Define Models: Django models are Python classes that represent database tables. Each
attribute in the class corresponds to a field in the table. Models are defined in the `models.py`
file of Django apps.

class Blog(models.Model):
name = models.CharField(max_length=50)
tagline = models.TextField()
# author = models.CharField(max_length=20,default = "")

def __str__(self):
return self.name

class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()

def __str__(self):
return self.name

2. Migrate Models: After defining models, run the `makemigrations` and `migrate` commands
to create corresponding database tables based on the model definitions.

python manage.py makemigrations


python manage.py migrate

36
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

3. Perform Queries: Django provides a powerful API for querying databases using model
objects. Various methods are available to perform CRUD operations, filter data, perform
aggregations, and more.

def table(request):
a = userregister.objects.get(name = 'a')
print(a)
for i in a:
print(i.email)
return render(request,'table.html',{'data':a})

37
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 12
Validations in the Django Models

Custom field validations in Django models can be implemented using the `clean()` method or by
overriding the `save()` method. Here's how you can implement custom field validations using
both methods:

class vendor(models.Model):

name = models.CharField(max_length=50)

email = models.EmailField()

mob = models.CharField(max_length=10)

add = models.TextField()

password = models.CharField(max_length=10)

typeofbusiness = models.CharField(max_length = 100)

def __str__(self):

return self.name

class order(models.Model):

userid = models.CharField(max_length = 10)

proid = models.CharField(max_length = 10)

totalamount = models.CharField(max_length = 10)


38
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

qty = models.CharField(max_length = 10)

add = models.TextField()

city = models.CharField(max_length = 30)

state =models.CharField(max_length = 30)

pincode = models.CharField(max_length = 6)

paymentype = models.CharField(max_length = 30)

transactionid = models.CharField(max_length = 100)

datetime = models.DateTimeField(auto_now = True)

def __str__(self):

return self.userid

The `clean()` method is overridden to perform custom validation on the `your_field` attribute. If
the validation fails, a `ValidationError` is raised. Make sure to call the parent class's `clean()`
method at the end of your custom `clean()` method.

39
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

class cart(models.Model):

productid = models.CharField(max_length=10)

userid = models.CharField(max_length=10)

quantity = models.CharField(max_length=10)

totalprice = models.CharField(max_length=10)

orderid = models.CharField(max_length=10)

def __str__(self):

return self.userid

The `save()` method is overridden to perform custom validation before saving the object. If the
validation fails, a `ValidationError` is raised. Make sure to call the parent class's `save()` method
at the end of your custom `save()` method.

Choose the method that best fits your use case. Generally, the `clean()` method is preferred for
field-specific validations, while the `save()` method is more suitable for object-level validations.

In Django, the `Meta` inner class within a model allows you to define metadata about the model.
This metadata can include options such as database table name, ordering, indexes, permissions,
and more. Here's an example of how you can use the `Meta` class in Django models:

40
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

- The `Meta` class is used to define metadata for the `YourModel` class.

- `verbose_name` specifies a human-readable name for the model. It's used in various Django
admin interfaces.

- `verbose_name_plural` specifies the plural form of the model name.

- `ordering` specifies the default ordering for queries on this model. In this case, it orders the
query results by the `field2` attribute in descending order.

You can include other options in the `Meta` class based on your requirements. Here are some
other common options:

- `db_table`: Specifies the name of the database table for the model.

- `unique_together`: Specifies sets of fields that, taken together, must be unique.

- `indexes`: Specifies database indexes for one or more fields.

- `permissions`: Specifies permissions associated with the model.

41
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 13
Filters in Python

In Python, filters are a way to selectively extract elements from a collection (like a list) based on
a condition. They're particularly useful when you want to apply a certain criterion to each
element of a collection and only retain those elements that satisfy the criterion.

The `filter()` function in Python takes two arguments: a function (or `None`) and an iterable (like
a list). It returns an iterator yielding those items of the iterable for which the function returns
true. If the function is `None`, it simply returns the elements that are true.

Here's a basic example to illustrate how `filter()` works:

def index(request):
if 'email' in request.session:
b = userregister.objects.get(email = request.session['email'])
a = category.objects.all()
return render(request,'index.html',{'category':a,'session':b})
elif 'vendoremail' in request.session:
a = category.objects.all()
b = vendor.objects.get(email = request.session['vendoremail'])
return render(request,'index.html',{'category':a,'vensession':b})
else:
a = category.objects.all()
return render(request,'index.html',{'category':a})

42
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

def reg(request):
# c = userregister.objects.get(name = 'b')
if request.method == 'POST':
a = userregister()
a.name = request.POST['uname']
a.email = request.POST['email']
a.mob = request.POST['mob']
a.add = request.POST['add']
pasword = request.POST['password']
print(pasword,"1111111111111111111111111111111111111")
encrypted_pass = encrypt(pasword)
print(encrypted_pass,"2222222222222222222222")
# check_password(encrypted_pass, pasword)
a.password = encrypted_pass
b = userregister.objects.filter(email = request.POST['email'])
error_msg = None
if a.email:
if len(a.mob) == 10:
if len(b) > 0:
return render(request,'register.html',{'email':'This email is already registered..'})
else:
if request.POST['password'] == request.POST['cp']:
a.save()
return render(request,'register.html',{'save':'Data stored succesfully....'})
else:
return render(request,'register.html',{'pass':'Passwords did not matched...'})
else:
error_msg = "Phone number must be 10 didgits.."
return render(request,'register.html',{'error':error_msg})
else:
error_msg = "Email field is required.."
return render(request,'register.html',{'error':error_msg})
else:
return render(request,'register.html',{})

This is a basic example of how you can implement product functionality using ORM queries
with SQLAlchemy in Python. Depending on your specific requirements and database schema,
you may need to adjust the code accordingly.

43
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 14
Web Page and Navigation using Session

To build a common web page with navigation using sessions in Python, you typically use a web
framework like Flask or Django. Here's an example using Flask, a lightweight and easy-to-use
web framework:

1. First, you need to install Flask if you haven't already:

pip install flask

2. Now, let's create a simple Flask application that demonstrates session-based navigation. We'll
have three pages: Home, About, and Contact.

from flask import Flask, render_template, session, redirect, url_for

app = Flask(__name__)
app.secret_key = 'your_secret_key' # Needed for session encryption

@app.route('/')
def home():
return render_template('home.html')

@app.route('/about')
def about():
return render_template('about.html')

@app.route('/contact')
def contact():
return render_template('contact.html')

@app.route('/login')
def login():
# Here you can set session variables like user authentication status, etc.
session['logged_in'] = True
return redirect(url_for('home'))

@app.route('/logout')

44
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

def logout():
# Clear session variables
session.clear()
return redirect(url_for('home'))

if __name__ == '__main__':
app.run(debug=True)

3. Create HTML templates for each page. You can use Jinja2 templating engine provided by
Flask for dynamic content.

`templates/home.html`:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
<h1>Home Page</h1>
<p>Welcome to our website!</p>
<nav>
<a href="/">Home</a> |
<a href="/about">About</a> |
<a href="/contact">Contact</a>
{% if session.logged_in %}
| <a href="/logout">Logout</a>
{% else %}
| <a href="/login">Login</a>
{% endif %}
</nav>
</body>
</html>

`templates/about.html`:
<!DOCTYPE html>
<html lang="en">
<head>
45
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>About</title>
</head>
<body>
<h1>About Us</h1>
<p>We are a company that does amazing things.</p>
<nav>
<a href="/">Home</a> |
<a href="/about">About</a> |
<a href="/contact">Contact</a>
{% if session.logged_in %}
| <a href="/logout">Logout</a>
{% else %}
| <a href="/login">Login</a>
{% endif %}
</nav>
</body>
</html>

`templates/contact.html`:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact</title>
</head>
<body>
<h1>Contact Us</h1>
<p>You can reach us at: [email protected]</p>
<nav>
<a href="/">Home</a> |
<a href="/about">About</a> |
<a href="/contact">Contact</a>
{% if session.logged_in %}
| <a href="/logout">Logout</a>
{% else %}
| <a href="/login">Login</a>
{% endif %}

46
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

</nav>
</body>
</html>

4. Run your Flask application:

python your_app_name.py

Now, you can navigate through the pages and see that the navigation bar updates based on
whether the user is logged in or not. The `session` object is used to keep track of the user's
authentication status across requests. When the user logs in or logs out, the `session` object is
updated accordingly.

Activity 2:Wishlist Management for the ecommerce in python with django


Prompt: Wishlist Management for the ecommerce in python with django

Implementing wishlist management for an e-commerce platform using Django involves creating
models, views, templates, and handling user authentication. Here's a step-by-step guide to
achieve this:

1. Set up Django Project: If you haven't already, create a Django project and app:

```bash
django-admin startproject ecommerce_project
cd ecommerce_project
python manage.py startapp wishlist
```

2. **Define Models**: Define the models for the wishlist functionality. A basic model might
look like this:

```python
# In wishlist/models.py

from django.db import models


from django.contrib.auth.models import User

class WishlistItem(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)

47
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

product_name = models.CharField(max_length=100)
product_description = models.TextField()
added_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.product_name
```

3. **Create Views**: Create views to handle adding, viewing, and removing items from the
wishlist.

```python
# In wishlist/views.py

from django.shortcuts import render, redirect


from django.contrib.auth.decorators import login_required
from .models import WishlistItem

@login_required
def wishlist(request):
wishlist_items = WishlistItem.objects.filter(user=request.user)
return render(request, 'wishlist/wishlist.html', {'wishlist_items': wishlist_items})

@login_required
def add_to_wishlist(request, product_id):
# Logic to add product to wishlist
pass

@login_required
def remove_from_wishlist(request, product_id):
# Logic to remove product from wishlist
pass
```

4. **Create URLs**: Define URLs for the wishlist views.

```python
# In wishlist/urls.py

from django.urls import path

48
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

from . import views

urlpatterns = [
path('', views.wishlist, name='wishlist'),
path('add/<int:product_id>/', views.add_to_wishlist, name='add_to_wishlist'),
path('remove/<int:product_id>/', views.remove_from_wishlist,
name='remove_from_wishlist'),
]
```

5. **Set up Templates**: Create templates for displaying the wishlist.

```html
<!-- In templates/wishlist/wishlist.html -->

{% extends 'base.html' %}
{% block content %}
<h1>Wishlist</h1>
{% if wishlist_items %}
<ul>
{% for item in wishlist_items %}
<li>{{ item.product_name }} - {{ item.product_description }}</li>
{% endfor %}
</ul>
{% else %}
<p>Your wishlist is empty.</p>
{% endif %}
{% endblock %}
```

6. **Wire up Authentication**: Ensure user authentication is set up properly in your Django


project.

7. **Include Wishlist URLs**: Include wishlist URLs in the main project's URL configuration.

```python
# In ecommerce_project/urls.py

from django.contrib import admin


from django.urls import path, include

49
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

urlpatterns = [
path('admin/', admin.site.urls),
path('wishlist/', include('wishlist.urls')),
]
```

8. **Run Migrations**: Run migrations to create the necessary database tables.

```bash
python manage.py makemigrations
python manage.py migrate
```

9. **Add Links to Wishlist**: In your e-commerce platform's product pages, add links to
add/remove products from the wishlist.

This is a basic outline to get you started with wishlist management in Django. Depending on
your specific requirements, you may need to extend this functionality further, such as adding
AJAX support for adding/removing items, handling quantity, etc.

50
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 15
SQLite Database integration in Django

SQLite is a lightweight and serverless database engine that is well-suited for development and
small-scale applications. Django, a high-level Python web framework, supports SQLite out of
the box, making it easy to get started with database-driven web applications.

Here's an overview of how to use SQLite database with Django and how to establish a
connection:

1. **Configure Django Settings**:


In your Django project's settings file (`settings.py`), ensure that Django is configured to use
SQLite as the default database engine. By default, Django comes pre-configured to use SQLite
for development purposes.

```python
#In settings.py

DATABASES={
‘default’:{
‘ENGINE’:’django.db.backends.sqlite3’,
‘NAME’:’django.db.backends.sqlite3’,
}
}
’’’

2. **Create Django Models**:


Define your application's data models using Django's ORM (Object-Relational Mapping).
These models will be used to create corresponding database tables.
```python
#In models.py
from django.db import models
class Product(models.Model):
name=models.CharField(max_length=100)
description=models.TextField()
price=models.DecimalField(max_digit=10,decimal_placesd=2)
‘’’

51
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

3. **Make Migrations**:
Django's migration system allows you to propagate changes you make to your models (adding
fields, deleting models, etc.) into your database schema.

```bash
Python manage.py makemigrations
```
This command creates migration files based on the changes detected in your models.

4. **Apply Migrations**:
Apply the migrations to create the corresponding database tables.

```bash
Python manage.py makemigrate
```
This command executes the migration files to create the database tables.

5. **Interact with the Database**:


Now that your database is set up, you can interact with it using Django's ORM. You can
perform CRUD (Create, Read, Update, Delete) operations on your models.

```python
#In views.py
from django.shortcuts import render
from.models import Product
def product_list(request)
product=Product.object.all()
return render(request,’product_list.html’,{‘products’:products})
```
6. **Run Django Development Server**:
Start the Django development server to test your application.
```bash
python manage.py runserver
```
7. **Access Admin Interface (Optional)**:
Django provides a built-in admin interface that allows you to perform CRUD operations on
your models. To access it, you need to create a superuser first.
```bash
Python manage.py createsuperuser

52
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

```

Follow the prompts to create a superuser, and then you can access the admin interface at
`http://localhost:8000/admin`.

That's it! You've established a connection to SQLite database in Python with Django and created
models to interact with the database. You can now start building your web application with
Django and SQLite.

To use MySQL with Django, you need to set up your Django project to use the MySQL database
engine. Here's how you can create and operate a MySQL database in Python with Django:

1. **Install MySQL Database Server**:


First, ensure that you have MySQL installed on your system. You can download and install
MySQL from the official website: [MySQL Downloads](https://dev.mysql.com/downloads/)

2. **Install MySQL Client Library**:


You also need to install the MySQL client library for Python. You can install it using pip:

```bash
pip install mysqlclient
```

3. **Create MySQL Database**:


Create a new database in your MySQL server that will be used by your Django project.

4. **Configure Django Settings**:


In your Django project's settings file (`settings.py`), update the database configuration to use
MySQL.

```python
# In settings.py

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'your_database_name',
'USER': 'your_mysql_username',

53
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

'PASSWORD': 'your_mysql_password',
'HOST': 'localhost', # Or the hostname of your MySQL server
'PORT': '3306', # Default MySQL port
}
}
```

Replace `'your_database_name'`, `'your_mysql_username'`, and `'your_mysql_password'` with


your actual MySQL database name, username, and password.

5. **Create Django Models**:


Define your Django models as you would normally. Here's an example:

```python
# In models.py

from django.db import models

class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
```

6. **Make Migrations and Apply Migrations**:


Run the following commands to create and apply migrations:

```bash
python manage.py makemigrations
python manage.py migrate
```

7. **Interact with the Database**:


Now you can interact with your MySQL database using Django's ORM. For example, you can
create, read, update, and delete records:

```python
# In views.py

from django.shortcuts import render

54
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

from .models import Product

def product_list(request):
products = Product.objects.all()
return render(request, 'product_list.html', {'products': products})
```

8. **Run Django Development Server**:


Start the Django development server to test your application:

```bash
python manage.py runserver
```

By following these steps, you can create and operate a MySQL database in Python with Django.
Ensure that your MySQL server is running and accessible from your Django project.

55
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 16
Razorpay Django

To integrate Razorpay payment gateway with Django, you need to follow these steps:

1. **Create a Razorpay Account**:


Sign up for a Razorpay account if you haven't already. Once signed up, you will get access to
the Razorpay dashboard where you can generate API keys.

2. **Install Razorpay Python SDK**:


You can use the official Razorpay Python SDK to integrate Razorpay with your Django
project. Install it using pip:

```bash
pip install razorpay
```

3. **Configure Razorpay API Keys**:


In your Django settings file (`settings.py`), add your Razorpay API keys:

```python
# In settings.py

RAZORPAY_API_KEY = 'your_api_key'
RAZORPAY_API_SECRET = 'your_api_secret'
```

4. **Create Payment Form**:


Create a form in your Django template where users can enter payment details:

```html
<!-- In payment_form.html -->

<form id="paymentForm" action="{% url 'process_payment' %}" method="POST">


{% csrf_token %}
<input type="text" name="amount" placeholder="Amount">
<input type="submit" value="Pay Now">
</form>
```

56
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

5. **Process Payment View**:


Create a view in Django to handle payment processing:

```python
# In views.py

from django.shortcuts import render


from django.http import JsonResponse
import razorpay
from django.conf import settings

def process_payment(request):
if request.method == 'POST':
amount = int(request.POST['amount']) * 100 # Convert amount to paisa (Razorpay
expects amount in paisa)
client = razorpay.Client(auth=(settings.RAZORPAY_API_KEY,
settings.RAZORPAY_API_SECRET))
payment_data = {
'amount': amount,
'currency': 'INR',
'receipt': 'order_rcptid_11',
'payment_capture': '1'
}
payment = client.order.create(data=payment_data)
return JsonResponse(payment)
return render(request, 'payment_form.html')
```

6. **Handle Payment Response**:


After the payment is processed, Razorpay will send a webhook or redirect the user back to a
URL specified by you. You need to handle this response to update the payment status in your
database.

7. **Update Payment Status View**:


Create a view to handle the payment status update:

```python
# In views.py

57
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

def update_payment_status(request):
if request.method == 'POST':
# Process Razorpay payment webhook or redirect response
# Update payment status in your database
return JsonResponse({'status': 'Payment status updated successfully'})
```

8. **URL Configuration**:
Configure URLs to map views:

```python
# In urls.py

from django.urls import path


from . import views

urlpatterns = [
path('', views.process_payment, name='process_payment'),
path('update_payment_status/', views.update_payment_status,
name='update_payment_status'),
]
```

9. **Update Templates**:
Update your templates to include the payment form and handle payment responses.

10. **Testing**:
Test the payment flow in your development environment. Ensure that payments are processed
successfully and payment status is updated in your database.

Remember to handle exceptions and errors gracefully, and follow best practices for security,
such as validating input and using HTTPS for sensitive transactions. Additionally, refer to the
Razorpay documentation for more details on handling webhooks and verifying payment
responses.

58
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 17
Git hub version control

Version control and collaboration using Git and GitHub are essential for managing Python and
Django projects effectively, especially when working in teams or contributing to open-source
projects. Here's an overview of how Git and GitHub are used in Python and Django
development:

### Version Control with Git:

1. **What is Version Control?**


Version control is a system that records changes to a file or set of files over time so that you
can recall specific versions later. Git is one of the most popular distributed version control
systems.

2. **Basic Concepts:**
- **Repository (Repo):** A repository is a collection of files and their revision history. It can
exist locally on your machine or remotely on a server.
- **Commit:** A commit is a snapshot of the repository at a specific point in time. It records
changes to one or more files.
- **Branch:** A branch is a parallel version of a repository. It allows you to work on new
features or fixes without affecting the main codebase.
- **Merge:** Merging is the process of combining changes from one branch into another.
- **Pull Request (PR):** A pull request is a request to merge changes from one branch into
another. It's commonly used for code review and collaboration.

3. **Workflow:**
- **Feature Branch Workflow:** Developers create a new branch for each new feature or bug
fix. Once the changes are complete, they create a pull request to merge their branch into the main
branch.

### Collaboration with GitHub:

1. **What is GitHub?**
GitHub is a web-based platform that provides hosting for Git repositories. It offers
collaboration features such as issue tracking, pull requests, and project management tools.

2. **Key Features:**
- **Repositories:** GitHub hosts repositories where you can store your code.

59
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

- **Issues:** You can create, assign, and track issues (bugs, feature requests, etc.) using
GitHub's issue tracker.
- **Pull Requests:** Pull requests facilitate code review and collaboration. They allow
contributors to propose changes and discuss them before merging into the main codebase.
- **Branch Protection:** GitHub allows you to protect certain branches from direct pushes and
require pull requests for changes, ensuring code quality and stability.
- **Actions and Workflows:** GitHub Actions enable you to automate workflows such as
testing, building, and deployment directly from your repository.

3. **Collaboration Workflow:**
- **Forking:** Contributors typically fork a repository to their account, make changes in their
forked repository, and then create a pull request to merge those changes back into the original
repository.
- **Code Review:** Pull requests enable code review by allowing team members to comment,
suggest changes, and discuss code changes before merging.
- **Continuous Integration (CI) / Continuous Deployment (CD):** GitHub Actions can be
used to set up CI/CD pipelines, automating the testing and deployment process.

### Summary:

Version control with Git and collaboration with GitHub are fundamental for managing Python
and Django projects efficiently. By leveraging these tools, developers can track changes,
collaborate effectively, and maintain code quality throughout the development lifecycle. Whether
working solo or in a team, understanding version control and collaboration workflows is crucial
for successful project management in Python and Django development.

Activity: Exception handling and ORM Queries for Login Management


Prompt: Exception handling and ORM Queries for Login Management in Python with Django

Exception handling and ORM queries are crucial aspects of implementing login management in
Python with Django. Below, I'll provide a basic example of how to handle exceptions and
perform ORM queries for login management in a Django project:

1. **Exception Handling**:
Exception handling is essential to gracefully handle errors that may occur during login
operations, such as invalid credentials or database errors. Django provides built-in mechanisms
for handling exceptions.

```python

60
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

from django.contrib.auth import authenticate, login


from django.contrib.auth.models import User
from django.http import Httpresponse
from django.shortcuts import render,redirect
def user_login(request):
if request.method==’POST’
username=request.POST.get(‘username’)
password==request.POST.get(‘password’)
user=authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect(‘home’)
else:
#Handle invalid credentials
Return render(request,’login.html’,{‘error’:’Invalid username or password’})
else:
return render(request,’login.html’)
```

2. **ORM Queries**:
Django's ORM (Object-Relational Mapping) provides a powerful interface for interacting with
the database. You can use ORM queries to retrieve user information from the database for
authentication purposes.

```python
From django.contrib.auth.models import User

def user_login(request):
if request.method==’POST’
username=request.POST.get(‘username’)
password==request.POST.get(‘password’)
try:
user=user.objects.get(username=username)
if user.check_password(password):
login(request,user)
login(request,user)
return redirect(‘home’)
else:
#Handle invalid password
Return render(request,’login.html’,{‘error’:’Invalid password’})

61
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Except User.DoesNotExit:
#Handle user not found
Return render(request,’login.html’,{‘error’:’User does not exist’})
else:
return render(request,’login.html’)
```

In this example, we attempt to retrieve the user from the database using `User.objects.get()` and
then validate the password using `user.check_password()`. We use exception handling
(`User.DoesNotExist`) to handle cases where the user does not exist in the database.

Ensure that you have a login template (`login.html`) where users can input their credentials and
submit the login form. Handle and display any error messages appropriately in the login
template.

By combining exception handling and ORM queries, you can implement robust login
management in Python with Django, ensuring that your application gracefully handles various
scenarios that may arise during the authentication process.

62
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 18
Django Email integration
Integrating email functionality into a Django project is a common requirement, whether it's for
user registration, password reset, or sending notifications. Django provides a convenient way to
handle email functionality through its built-in `send_mail()` function and EmailMessage class.
Here's how you can integrate email functionality into your Django project:

1. **Configure Email Settings in `settings.py`**:


First, configure the email backend settings in your Django project's `settings.py` file. You can
use SMTP for sending emails. Here's an example configuration using Gmail SMTP:

```python
#settings.py
EMAIL_BACKEND=’django.core.mail.backends.smtp.EmailBackend’
EMAIL_HOST=’smtp.gmail.com’
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_HOST_USER= ‘your [email protected]
EMAIL_HOST_PASSWORD=’your_email_password’
```
Replace `'[email protected]'` and `'your_email_password'` with your Gmail email
address and password. Alternatively, you can use other SMTP servers or email providers.

2. **Sending Email Using `send_mail()` Function**:


You can use the `send_mail()` function provided by Django to send simple emails. Here's an
example of sending a basic email:
```python
From django.core.mail import send_mail
Send mail(
‘Subject here’,
‘Here is the message’,
[email protected]’,
[‘[email protected]’],
fail_silently=False,
)
```

You can call this function from any Django view or task where you want to send an email.

63
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

3. **Sending Email Using `EmailMessage` Class**:


For more advanced email functionality, such as sending HTML emails or attaching files, you
can use the `EmailMessage` class. Here's an example:
```python
from django.core.mail import EmailMessage
email=EmailMessage(
‘Subject here’,
‘Here is the message’,
[email protected]’,
[‘[email protected]’],
)
Email.content_subtype=”html” #set the content type to HTML
Email.attach_file(‘/path/to/file.pdf’) #Attach a file
Email.send()
```
4. **Sending Templated Emails**:
You can use Django's template system to create HTML email templates. First, create an HTML
template for your email (e.g., `email_template.html`), then render it using Django's template
engine:
```python
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
html_content= render_to_string(‘email_templates.html’,{‘context_variable’:’value’})
email=EmailMessage(
‘Subject here’,
html_content,
[email protected]’,
[‘[email protected]’],
)
email.content_subtype=”html” #set the content type to HTML
Email.send()
```
Ensure that you have created a template file (`email_template.html`) in your Django templates
directory.

5. **Asynchronous Email Sending**:


For long-running tasks or when you want to offload email sending to a background process,
you can use Django's `django.core.mail.send_mail()` method with `asyncio` or `celery`.

64
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Here's a basic example using `asyncio`:


```python
Import asyncio
from django.core.mail import send_mail
async def send_email_async():
await asyncio.sleep(1) #Simulate asynchronous operation
send_mail(
‘Subject here’,
‘Here is the message’,
[email protected]’,
[‘[email protected]’],
fail_silently=False,

)
Asyncio.run(send_email_async())
```
For `celery`, you need to set up a Celery worker and task to handle email sending
asynchronously.

With these steps, you can integrate email functionality into your Python Django project, enabling
you to send various types of emails, including simple text emails, HTML emails, templated
emails, and asynchronously sent emails.

65
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 19
Ecom Cart

Implementing cart management for an e-commerce website using Python and Django involves
several steps. Below is a basic guide on how to implement cart functionality:

1. **Create Cart Model**:


First, create a model to represent the cart and its items in your Django application.

def cartdata(request):
if 'email' in request.session:
prolist = []
b = userregister.objects.get(email = request.session['email'])
a = cart.objects.filter(userid = request.session['userid'],orderid = "0")
print(a,11111111111111111111111111111111111111111)
totalamount = 0
for i in a:
totalamount += int(i.totalprice)
pro = product.objects.get(id = i.productid)
prodict =
{'id':i.productid,'proimage':pro.image,'proprice':pro.price,'total':i.totalprice,'userqty':i.quantit
y}
prolist.append(prodict)
if 'stock' in request.session:
del request.session['stock']
return render(request,'cart.html',
{'session':b,'prolist':prolist,'totalamount':totalamount,'stock':"Kale avje!!"})
else:
return render(request,'cart.html',
{'session':b,'prolist':prolist,'totalamount':totalamount})
return render(request,'cart.html',{'session':b,'prolist':prolist,'totalamount':totalamount})
else:
return redirect('login')

2. **Add Cart**:

66
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Associate each user with their cart. You can do this by extending the user model or using a
OneToOneField to link users to their carts.

def additem(request,id):
if 'email' in request.session:
# b = userregister.objects.get(email = request.session['email'])
a = cart.objects.get(userid = request.session['userid'],productid = id,orderid = "0")
b = product.objects.get(id = a.productid)
if b.qty <= 0:
request.session['stock'] = 0
return redirect('cart')
else:
a.quantity = int(a.quantity) + 1
a.totalprice= int(a.totalprice) + int(b.price)
a.save()
b.qty = b.qty - 1
b.save()
print(a,"cart qunatity 11111111111111111111111111111111111")
return redirect('cart')
else:
return redirect('login')

67
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 20
Remove Cart Function

def minus(request,id):
if 'email' in request.session:
a = cart.objects.get(userid = request.session['userid'],productid = id,orderid = "0")
b = product.objects.get(id = a.productid)
if int(a.quantity) <= 1:
a.delete()
return redirect('cart')
else:
a.quantity = int(a.quantity) - 1
a.totalprice= int(a.totalprice) - int(b.price)
a.save()
b.qty = int(b.qty) + 1
b.save()
return redirect('cart')
else:
return redirect('login')

Remove all items makes cart empty, so user have to add again products into the cart. It will also
completely remove the data from the model itself.

def removeall(request):
if 'email' in request.session:
a = cart.objects.filter(userid = request.session['userid'])
for i in a:
b = product.objects.get(id = i.productid)
b.qty = int(b.qty) + int(i.quantity)
b.save()
a.delete()
return redirect('cart')

68
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

else:
return redirect('login')

69
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 21
Cart Template

1. cart.html

{% extends "nav.html" %}
{% load static %}
{% block abc %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<title>E-commerce</title>
<link
rel="stylesheet"
45

href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.mi
n.css"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/
all.min.css"
integrity="sha512-
z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBre
CFkKxLhei6S9CQXFEbbKuqLg0DA=="

70
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js
"></script>
<link rel="stylesheet" href={% static "css/ecom.css" %} />
</head>
<body>
<!--====================== Navbar
======================-->

<!--====================== Cart Section


======================-->
<div class="container mt-5">
<h1 class="mb-4">Your Shopping Cart</h1>
<div class="row">
<div class="col-md-8">
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<th class="align-bottom pb-2">
<a href={% url "removeall" %}><button class="btn btn-

71
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

outline-danger">Remove All</button></a>
</th>
</tr>
</thead>
<tbody>
{% for i in prolist %}
<tr class="align-content-center">
<td>
<img src={{i.proimage.url}} alt="" height="200px"
width="200px" />
</td>
<td>₹{{i.proprice}}</td>
<td>
<a href={% url "add1" i.id %}><button class="increase
items-count btn mr-1" type="button">
<i class="fa fa-plus text-dark"></i>
</button></a>
<button class="border-0 btn">{{i.userqty}}</button>
<a href={% url "minus" i.id %}><button class="increase
items-count btn" type="button">
<i class="fa fa-minus text-dark"></i>
</button></a>
</td>
<td>₹{{i.total}}</td>
<td class="align-bottom pb-3">
<button class="btn btn-outline-danger">Remove</button>
</td>
</tr>

72
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

{% endfor %}
</tbody>
</table>
</div>
<div class="col-md-3 ml-auto mt-0 pt-0">

<div class="card p-2">


<div class="card-body">
<h5 class="card-title">Summary</h5>
<hr />
<p><strong>Total: </strong>₹{{totalamount}}</p>
<a href={% url "checkout" %}>
<button class="btn btn-outline-success btn-block">
Checkout
</button>
</a>
</div>
</div>
</div>
{% if stock %}
<script>
alert('{{stock}}')
</script>
{% endif %}
</div>
</div>
<!--======================Footer
Section======================-->

73
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<footer class="bg-dark text-light py-4">


<div class="container">
<div class="row">
<div class="col-md-4">
<h5>Contact Us</h5>
<p>Email: [email protected]</p>
<p>Phone: 123-456-7890</p>
</div>
<div class="col-md-4">
<h5>Links</h5>
<ul class="list-unstyled">
<li><a href="#">Home</a></li>
<li><a href="#">Products</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
<div class="col-md-4">
<h5>Follow Us</h5>
<ul class="list-inline">
<li class="list-inline-item">
<a href="#"><i class="fab fa-facebook"></i></a>
</li>
<li class="list-inline-item">
<a href="#"><i class="fab fa-twitter"></i></a>
</li>
<li class="list-inline-item">

74
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<a href="#"><i class="fab fa-instagram"></i></a>


</li>
</ul>
</div>
</div>
<hr />
<div class="row">
<div class="col text-center">
<p>&copy; 2023 Your E-Commerce Store</p>
</div>
</div>
</div>
</footer>
</body>
</html>
{% endblock abc %}

75
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 22
Checkout Template

1. checkout.html

{% extends 'nav.html' %}
{% block abc %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="Mark Otto, Jacob Thornton, and
Bootstrap contributors">
<meta name="generator" content="Hugo 0.101.0">
<title>Checkout example · Bootstrap v4.6</title>

<link rel="canonical"
href="https://getbootstrap.com/docs/4.6/examples/checkout/">

<!-- Bootstrap core CSS -->


<link
href="https://getbootstrap.com/docs/4.6/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy
4HI+N" crossorigin="anonymous">

76
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<!-- Favicons -->


<link rel="apple-touch-icon" href="/docs/4.6/assets/img/favicons/apple-
touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/4.6/assets/img/favicons/favicon-32x32.png"
sizes="32x32" type="image/png">
<link rel="icon" href="/docs/4.6/assets/img/favicons/favicon-16x16.png"
sizes="16x16" type="image/png">
<link rel="manifest"
href="/docs/4.6/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/4.6/assets/img/favicons/safari-pinned-
tab.svg" color="#563d7c">
<link rel="icon" href="/docs/4.6/assets/img/favicons/favicon.ico">
<meta name="msapplication-config"
content="/docs/4.6/assets/img/favicons/browserconfig.xml">
<meta name="theme-color" content="#563d7c">

<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

77
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

@media (min-width: 768px) {


.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
.reveal-if-active {
opacity: 0;
max-height: 0;
overflow: hidden;
}
input[type="radio"]:checked ~ .reveal-if-active{
opacity: 1;
max-height: 100px; /* little bit of a magic number :( */
overflow: visible;
}

</style>

<!-- Custom styles for this template -->


<link href="form-validation.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container">
<div class="py-5 text-center">
{% comment %} <img class="d-block mx-auto mb-4"
78
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

src="https://getbootstrap.com/docs/4.6/assets/brand/bootstrap-solid.svg"
alt="" width="72" height="72"> {% endcomment %}
<h2>Checkout form</h2>
{% comment %} <p class="lead">Below is an example form built
entirely with Bootstrap’s form controls. Each required form group has a
validation state that can be triggered by attempting to submit the form
without completing it.</p> {% endcomment %}
</div>

<div class="row">
<div class="col-md-4 order-md-2 mb-4">
<h4 class="d-flex justify-content-between align-items-center mb-3">
<span class="text-muted">Your cart</span>
<span class="badge badge-secondary badge-pill">3</span>
</h4>
{% for i in prolist %}
<ul class="list-group mb-3">
<li class="list-group-item d-flex justify-content-between lh-
condensed">
<div>
<div>
<img src="{{i.proimg.url}}" alt="" style="height: 25%; width:
25%;">
</div>
<h6 class="my-0">{{i.proname}}</h6>
<small class="text-muted">Discrption:{{i.prodis}}</small>
<div>
<span class="text-muted">Price:{{i.proprice}}</span>
</div>

79
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<span class="text-muted">Quantity:{{i.cartqty}}</span>
<span class="text-muted">price of your qty:
{{i.prototalprice}}</span>

</div>
</li>
{% endfor %}
<li class="list-group-item d-flex justify-content-between">
<span>Total </span>
<strong>{{grandtotal}}</strong>
</li>

</ul>

<form class="card p-2">


<div class="input-group">
{% comment %} <input type="text" class="form-control"
placeholder="Promo code">
<div class="input-group-append">
<button type="submit" class="btn
btn-secondary">Redeem</button>
</div> {% endcomment %}
</div>
</form>
</div>
<div class="col-md-8 order-md-1">
<h4 class="mb-3">Billing address</h4>

80
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<form class="needs-validation" novalidate method="post">


{% csrf_token %}
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" id="firstName"
placeholder="" value="{{session.name}}" required name="name">
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
</div>

<div class="mb-3">
<label for="email">Email <span
class="text-muted"></span></label>
<input type="email" class="form-control" id="email"
placeholder="[email protected]" name='email' required
value={{session.email}} readonly>
<div class="invalid-feedback">
Please enter a valid email address for shipping updates.
</div>
</div>

<div class="mb-3">
<label for="email">Mobile Number <span class="text-
muted"></span></label>
<input type="text" class="form-control" id="email"
placeholder="+91 " name='mob' required value={{session.mob}} >

81
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<div class="invalid-feedback">
Please enter a valid email address for shipping updates.
</div>
</div>

<div class="mb-3">
<label for="address">Address</label>
<input type="text" class="form-control" id="address"
placeholder="1234 Main St" required name='add'
value="{{session.add}}" >
<div class="invalid-feedback">
Please enter your shipping address.
</div>
</div>

<div class="mb-3">
<label for="address2">City <span
class="text-muted"></span></label>
<input type="text" class="form-control" id="address2"
placeholder="city" name='city' required value="">
</div>

<div class="row">

<div class="col-md-4 mb-3">


<label for="state">State</label>
<input type="text" class="form-control" id="address2"
placeholder="state" name='state' required value="{{a.state}}">
</div>

82
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<div class="col-md-3 mb-3">


<label for="zip">Zip</label>
<input type="text" class="form-control" id="zip"
placeholder="Pincode" required name='pin' value="{{a.pincode}}">
<div class="invalid-feedback">
Zip code required.
</div>
</div>
</div>
<hr class="mb-4">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="same-
address">
<label class="custom-control-label" for="same-address">Shipping
address is the same as my billing address</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="save-
info">
<label class="custom-control-label" for="save-info">Save this
information for next time</label>
</div>
<hr class="mb-4">

<h4 class="mb-3">Payment</h4>

<div class="d-block my-3">


<div class="custom-control custom-radio">
<input id="online" name="paymentvia" type="radio"

83
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

class="custom-control-input" value="online">
<label class="custom-control-label" for="online">Online</label>
</div>
<div class="custom-control custom-radio">
<input id="cod" name="paymentvia" type="radio"
class="custom-control-input" value="cod">
<label class="custom-control-label" for="cod">Cash on
Delivery</label>
</div>
</div>
<hr class="mb-4">
<button class="btn btn-primary btn-lg btn-block"
type="submit">Continue to checkout</button>
{% comment %} <button class="btn btn-primary btn-lg btn-block"
type="submit" id="pay-btn">Make Payment</button> {% endcomment
%}
</form>
</div>
</div>

<footer class="my-5 pt-5 text-muted text-center text-small">


<p class="mb-1">&copy; 2017-2022 Company Name</p>
<ul class="list-inline">
<li class="list-inline-item"><a href="#">Privacy</a></li>
<li class="list-inline-item"><a href="#">Terms</a></li>
<li class="list-inline-item"><a href="#">Support</a></li>
</ul>
</footer>
</div>

84
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBn
E+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script
src="/docs/4.6/assets/js/vendor/jquery.slim.min.js"><\/script>')</
script><script src="/docs/4.6/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5V
g3Q9ct" crossorigin="anonymous"></script>

</body>
</html>
{% endblock abc %}

85
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 23
Product Template

1. product.html

{% extends "nav.html" %}
{% block abc %}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0" />
<title>E-commerce</title>
<link
rel="stylesheet"
45

href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.mi
n.css"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/
all.min.css"
integrity="sha512-
z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBre
CFkKxLhei6S9CQXFEbbKuqLg0DA=="

86
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js
"></script>
<link rel="stylesheet" href={% static "css/ecom.css" %} />
</head>
<body>
<!--====================== Navbar
======================-->

<!--====================== Main Section


======================-->
<div class="container my-5">
<div class="row mt-4 mr-auto ml-auto">
<div class="col-lg-4">

<img
src={{prodetails.image.url}}
alt="Product Image"
class="img-fluid"
height="500px"
width="300px"
/>

87
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

</div>
<div class="col-lg-6 mr-auto ml-auto mt-5">
<h1>{{prodetails.name}}</h1>
<p>
{{prodetails.discrption}}
</p>
<p><strong>Price:</strong> ₹{{prodetails.price}}</p>
<form action="" method="post">
{% csrf_token %}
<input type="number" minlength="1" name="qty">
<i class="fa-solid fa-star ratingcolor"></i>
<i class="fa-solid fa-star ratingcolor"></i>
<i class="fa-solid fa-star ratingcolor"></i>
<i class="fa-regular fa-star-half-stroke ratingcolor"></i>
<i class="fa-regular fa-star ratingcolor"></i>
<br />
<a href="cart.html">
<button class="btn btn-outline-primary mt-3">Add to
Cart</button>
</a>
</form>
{% if chej %}
<script>
alert('{{chej}}')
</script>
{% endif %}
</div>
</div>

88
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

</div>

<!--======================Footer
Section======================-->
<footer class="bg-dark text-light py-4">
<div class="container">
<div class="row">
<div class="col-md-4">
<h5>Contact Us</h5>
<p>Email: [email protected]</p>
<p>Phone: 123-456-7890</p>
</div>
<div class="col-md-4">
<h5>Links</h5>
<ul class="list-unstyled">
<li><a href="#">Home</a></li>
<li><a href="#">Products</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
<div class="col-md-4">
<h5>Follow Us</h5>
<ul class="list-inline">
<li class="list-inline-item">
<a href="#"><i class="fab fa-facebook"></i></a>
</li>
<li class="list-inline-item">

89
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<a href="#"><i class="fab fa-twitter"></i></a>


</li>
<li class="list-inline-item">
<a href="#"><i class="fab fa-instagram"></i></a>
</li>
</ul>
</div>
</div>
<hr />
<div class="row">
<div class="col text-center">
<p>&copy; 2023 Your E-Commerce Store</p>
</div>
</div>
</div>
</footer>
</body>
</html>
{% endblock abc %}

90
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 24

“Deployment”

Prompt: Website Deployment on Server

Deploying a Django project typically involves the following steps:

1. **Prepare your Django project for deployment:**


- Ensure your project is properly configured for production, including settings
related to database, static files, media files, security, and debugging.
- Update your `ALLOWED_HOSTS` setting in `settings.py` to include the
domain names or IP addresses of your production server(s).

2. **Choose a hosting provider:**


- Select a hosting provider that supports Django applications. Popular options
include Heroku, DigitalOcean, AWS (Amazon Web Services), Google Cloud
Platform, PythonAnywhere, and others.
- Consider factors such as pricing, scalability, performance, ease of use, and
support when choosing a hosting provider.

3. **Set up your server environment:**


- Provision a server instance (virtual private server or VPS) with your hosting
provider.
- Install necessary software on the server, such as Python, a web server (e.g.,
Nginx or Apache), and a database server (e.g., PostgreSQL, MySQL, or SQLite).
- Set up a domain name and configure DNS settings to point to your server's IP
address.

4. **Deploy your code to the server:**


- Upload your Django project files to the server using SSH, FTP, or a version
control system like Git.

91
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

- Set up a virtual environment on the server and install project dependencies


using pip.
- Configure the server to serve static files and media files (if applicable) using the
appropriate web server configuration.

5. **Configure the web server:**


- Set up Nginx or Apache to serve as a reverse proxy for your Django
application.
- Configure the web server to pass requests to the Django application using
WSGI (Web Server Gateway Interface) or ASGI (Asynchronous Server Gateway
Interface).

6. **Set up database and environment variables:**


- Create a database for your Django project and configure the database
connection settings in your `settings.py` file.
- Set up environment variables for sensitive information such as database
credentials, secret keys, and API keys.

7. **Collect static files:**


- Run the `collectstatic` management command to collect static files from your
Django apps into one location.
- Configure your web server to serve static files directly or use a content delivery
network (CDN) for improved performance.

8. **Test your deployment:**


- Access your Django application through the domain name or IP address of your
server.
- Test all functionality to ensure everything is working correctly in the
production environment.
- Monitor server logs and error messages for any issues that may arise.

9. **Implement security measures:**


- Enable HTTPS to encrypt traffic between the client and server.

92
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

- Implement security best practices, such as using strong passwords, keeping


software up-to-date, and configuring firewalls.

10. **Set up backups and monitoring:**


- Configure regular backups of your Django project files, database, and server
configuration.
- Set up monitoring tools to track server performance, uptime, and security
threats.

Remember to refer to the documentation of your hosting provider and follow their
specific guidelines for deploying Django applications. Additionally, consider
automating the deployment process using tools like Fabric, Ansible, or Docker for
easier management and scalability.

93
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 25

94
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 26

95
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 27

96
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 28

97
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 29

98
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 30

99
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 31
100
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

101
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 32

102
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 33

103
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 34

104
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 35
105
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 36

106
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 37

107
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 38

108
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 39

109
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 40

110
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 41

111
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 42

112
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 43

113
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 44

114
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Day 45

115
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Tasks
116
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Task 1: Project Planning

Define project scope, objectives, and requirements


#project_settings.py
PROJECT_NAME=”Ecommerce Website”
SCOPE=”To built a fully functional ecommerce platform using Django.”
OBJECTIVIES=[“Implement user authentication”, “Create product management system”,
“Integrate payment gateway”]

Task 2: Django Setup

Install Django framework.

pip install django

Task 3: Create Django Project

django-admin startproject ecommerce_project

Task 4: Database Design


Design the database schema.

# models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()

Task 5: Research and Analysis


117
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

 Analyze competitor websites for insights.


 Conduct market research on ecommerce trends.

Task 6: User Authentication


Implement user registration and login functionality.

# views.py
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login, authenticate

def register(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('/')
return render(request, 'registration/register.html', {'form': form})

Task 7: Product Management


Develop CRUD operations for products.
118
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

# views.py
from .models import Product
from django.shortcuts import render, get_object_or_404

def product_detail(request, product_id):


product = get_object_or_404(Product, pk=product_id)
return render(request, 'product/detail.html', {'product': product})

Task 8: Shopping Cart


Create a shopping cart system.

# models.py
class Cart(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
items = models.ManyToManyField(Product)
quantity = models.PositiveIntegerField(default=1)

119
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Task 9: Checkout Process


Design and implement a multi-step checkout process.

# views.py
def checkout(request):
if request.method == 'POST':
# Handle payment processing
return redirect('order_confirmation')
return render(request, 'checkout.html')

Task 10: User Profiles and Orders


Develop user profile pages.

# views.py
def profile(request):
user = request.user
orders = Order.objects.filter(user=user)
return render(request, 'profile.html', {'user': user, 'orders': orders})

Task 11: Backend Administration


Create an admin panel for site management.

# admin.py
from django.contrib import admin
from .models import Product, Order

admin.site.register(Product)

120
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

admin.site.register(Order)

Task 12: Base Page


Convert wireframes into responsive web pages.

<!-- base.html -->


<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>

Task 13: Encrypt Util


from cryptography.fernet import Fernet
import base64
import logging
import traceback
from django.conf import settings

def encrypt(pas):
try:
pas = str(pas)
cipher_pass = Fernet(settings.ENCRYPT_KEY)
encrypt_pass = cipher_pass.encrypt(pas.encode('UTF-8'))
encrypt_pass = base64.urlsafe_b64encode(encrypt_pass).decode("UTF-8")
return encrypt_pass
except Exception as e:
logging.getLogger("error_logger").error(traceback.format_exc())
return None

121
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Task 14: Decrypt Util


def decrypt(pas):
try:
pas = base64.urlsafe_b64decode(pas)
cipher_pass = Fernet(settings.ENCRYPT_KEY)
decod_pass = cipher_pass.decrypt(pas).decode("UTF-8")
return decod_pass
except Exception as e:
logging.getLogger("error_logger").error(traceback.format_exc())
return None

Task 15: App Info


from django.apps import AppConfig

class App1Config(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'app1'

Task 16: Mapping


from django.urls import path
from .views import *

urlpatterns = [
path('reg/',reg,name='userreg'),
# path('reg/',),
path('',index,name='index'),
path('table/',table,name='table'),
path('cat/',cat,name='cat'),
path('data/',data,name='data'),
path('img/',image,name='img'),
path('login/',login,name='login'),
path('logout/',logout,name='logout'),
path('profile/',profile,name='profile'),
path('card/<int:id>',card,name='card'),
path('pro/<int:id>',pro,name='pro'),
path('prodetails/<int:id>',prodetails,name='prodetails'),
path('cart/',cartdata,name='cart'),
path('add1/<int:id>',additem,name='add1'),
path('minus/<int:id>',minus,name='minus'),
path('removeall/',removeall,name='removeall'),
path('venreg/',venreg,name='venreg'),
path('venlogin/',venlogin,name='venlogin'),
path('addpro/',addproducts,name = 'addpro'),
path('venpro/',venpro,name = 'venpro'),
path('updatepro/<int:id>',updatepro,name='updatepro'),
path('deletepro/<int:id>',deletepro,name='deletepro'),
path('checkout/',checkout,name='checkout'),
path('orderhistory/',orderhistory,name='orderhistory'),
path('soldpro/',soldpro,name='soldpro'),
path('razorpay/',razorpaypayment,name= 'razorpay'),
122
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

path('paymenthandler/',paymenthandler,name='paymenthandler'),
path('otp/',otp,name='otp'),

Task 17: Database Config


DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'app1',
'HOST': '127.0.0.1',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'root',
}
}

Task 18: Static & Media Files

STATIC_URL = '/static/'

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

Task 19: Email Config

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'howk ouoo xljq lqwe'
EMAIL_USE_TLS = True
EMAIL_PORT = 587

123
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Task 20: Table Config


def table(request):
a = userregister.objects.get(name = 'a')
# print(a)
# for i in a:
# print(i.email)
return render(request,'table.html',{'data':a})

Task 21: Categories


def cat(request):
if 'email' in request.session:
b = userregister.objects.get(email = request.session['email'])
a = category.objects.all()
return render(request,'cat.html',{'cat':a,'session':b})
else:
a = category.objects.all()
return render(request,'cat.html',{'cat':a})

class category(models.Model):
catname = models.CharField(max_length=50)
image = models.ImageField(upload_to='imgcat')

def __str__(self):
return self.catname

Task 22: Ecom Data Store


def data(request):
if request.method == 'POST':
a = Blog()
a.name = request.POST['uname']
a.tagline = request.POST['data']
a.save()
print("data stored succesfullyy....")
return render(request,'form.html')
else:
print("failed to store data.......")
return render(request,'form.html')

124
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Task 23: Image Processing


def image(request):
if request.method == 'POST' and request.FILES['img']:
a = category()
a.catname = request.POST['uname']
a.image = request.FILES['img']
a.save()
# return render(request,'img.html')
return redirect('venlogin')
else:
return render(request,'img.html')

Task 24: OTP Config


def otp(request):
if request.method == 'POST':
if int(request.session['otp']) == int(request.POST['otp']):
return redirect('index')
else:
return render(request,'otp.html',{'invalid':"Invalid OTP"})

else:
return render(request,'otp.html')

Task 25: Profile Fetch


def profile(request):
if 'email' in request.session:
a = userregister.objects.get(email = request.session['email'])
if request.method == 'POST':
a.name = request.POST['uname']
a.mob = request.POST['mob']
a.add = request.POST['add']
a.save()
return render(request,'profile.html',{'session':a})
else:
return render(request,'profile.html',{'session':a})
else:
return redirect('login')

Task 26: Card


def card(request,id):
if 'email' in request.session:
b = userregister.objects.get(email = request.session['email'])
a = category.objects.get(id = id)
return render(request,'card.html',{'cat':a,'session':b})
else:
return redirect('login')

125
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Task 27: All Products Fetch


def pro(request,id):
if 'email' in request.session:
b = userregister.objects.get(email = request.session['email'])
a = product.objects.filter(category = id)
return render(request,'pro.html',{'pro':a,'session':b})
else:
return redirect('login')

Task 28: Products Details


def prodetails(request,id):
if 'email' in request.session:
b = userregister.objects.get(email = request.session['email'])
a = product.objects.get(id = id)
if request.method == 'POST':
cartdata = cart()
cartdata.productid = id
cartdata.userid = request.session['userid']
cartdata.quantity = request.POST['qty']
cartdata.totalprice = int(request.POST['qty']) * int(a.price)
cartdata.orderid = "0"
c = cart.objects.filter(productid = id,userid =
request.session['userid'],orderid = "0")
if c:
return render(request,'product.html',
{'session':b,'prodetails':a,'chej':'cheejjjj!!!'})
else:
cartdata.save()
a.qty = a.qty - int(request.POST['qty'])
a.save()
return render(request,'product.html',
{'session':b,'prodetails':a})
else:
return render(request,'product.html',{'session':b,'prodetails':a})
else:
return redirect('login')

Task 29: Update Product


def updatepro(request,id):
if request.method == 'POST':
a = product.objects.get(id = id)
a.price = request.POST['price']
a.qty = request.POST['qty']
a.discrption = request.POST['des']
a.save()
# return render(request,'updatepro.html',{'proupdatedetail':a})
return redirect('venpro')
126
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

else:
a = product.objects.get(id = id)
return render(request,'updatepro.html',{'proupdatedetail':a})

Task 30: Delete Product


def deletepro(request,id):
if 'vendoremail' in request.session:
ven = vendor.objects.get(email = request.session['vendoremail'])
a = product.objects.get(id = id)
a.delete()
return redirect('venpro')
else:
return redirect('venlogin')

Task 31: Product Sold


def soldpro(request):
if 'vendoremail' in request.session:
cartdata = cart.objects.all()
prolist= []
for i in cartdata:
print(i,"carrrtttt datatttttaa")
if i.orderid != "0":
print(i, "ordered dataaaaaa.......")
pro = product.objects.get(id = i.productid)
print(pro.name,"prooduct nameeeeeeeeee......")
print(request.session['vendorid'],pro.vendor,"vendooorrrrr
idd......")
if int(pro.vendor) == int(request.session['vendorid']):
print(pro.name,"product name of vendorr......")
userdetails = userregister.objects.get(id = i.userid)
prodict =
{'proimg':pro.image,'proname':pro.name,'qty':i.quantity,'uname':userdetails.na
me}
prolist.append(prodict)
return render(request,'soldpro.html',
{'prolist':prolist,'vensession':True})
else:
return redirect('venlogin')

Tast 32: Order History


def orderhistory(request):
if 'email' in request.session:
a = cart.objects.filter(userid = request.session['userid'])
prolist = []
for i in a:
if i.orderid != "0":
orderdt = order.objects.get(id = i.orderid)
prodetails = product.objects.get(id = i.productid)
prodict =
{'proname':prodetails.name,'proimg':prodetails.image,'prodis':prodetails.discr
127
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

ption,'datetime':orderdt.datetime,'qty':i.quantity,'tp':i.totalprice,'sp':prod
etails.price}
prolist.append(prodict)
else:
pass
# print(total,"totalll producttsss........")
return render(request,'orderhistory.html',
{'order':a,'prolist':prolist})
else:
return redirect('login')

Task 33: Landing Page


def index(request):
if 'email' in request.session:
b = userregister.objects.get(email = request.session['email'])
a = category.objects.all()
return render(request,'index.html',{'category':a,'session':b})
elif 'vendoremail' in request.session:
a = category.objects.all()
b = vendor.objects.get(email = request.session['vendoremail'])
return render(request,'index.html',{'category':a,'vensession':b})
else:
a = category.objects.all()
return render(request,'index.html',{'category':a})

Task 34: Razorpay Config


<!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>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
var options = {

// Enter the Key ID generated from the Dashboard


key: "{{ razorpay_merchant_key }}",

// Amount is in currency subunits.


// Default currency is INR. Hence,
// 50000 refers to 50000 paise
amount: "{{ razorpay_amount }}",
currency: 'INR',

// Your/store name.
name: "morning E-commerce",

// Pass the `id` obtained in the response of Step 1


order_id: "{{ razorpay_order_id }}",
128
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

callback_url: "{{ callback_url }}",


};

// initialise razorpay with the options.


var rzp1 = new Razorpay(options);
rzp1.open();

</script>
</body>
</html>

Task 35: Vendor Product


{% extends "nav.html" %}
{% block abc %}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>E-commerce</title>
<link
rel="stylesheet"
45

href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/
all.min.css"
integrity="sha512-
z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbb
KuqLg0DA=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></
script>
<link rel="stylesheet" href= {% static "ecom.css" %}/>
</head>
<body>
<!--====================== Navbar ======================-->

<!--======================Carousel Section======================-->
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>

129
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<div class="carousel-inner">
<div class="carousel-item active">
<img src="Img/151.jpg" alt="First Slide" />
</div>
<div class="carousel-item">
<img src="Img/6068656.jpg" alt="Second Slide" />
</div>
<div class="carousel-item">
<img src="Img/3671942.jpg" alt="Third Slide" />
</div>
</div>

<a
class="carousel-control-prev"
href="#myCarousel"
role="button"
data-slide="prev"
>
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a
class="carousel-control-next"
href="#myCarousel"
role="button"
data-slide="next"
>
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<!--======================Service Section======================-->
<section class="container-fluid py-2">
<div class="container">
<div class="row">
<div
class="col-4 d-flex justify-content-center align-items-center p-4"
>
<i class="fa-solid fa-truck-fast fa-2x mr-3"></i>
<p class="text-left p-0">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Dolorum
</p>
</div>
<div
class="col-4 d-flex justify-content-center align-items-center p-4"
>
<i class="fa fa-plane-circle-check fa-2x mr-3"></i>
<p class="text-left p-0">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Dolorum
</p>
</div>
<div
class="col-4 d-flex justify-content-center align-items-center p-4"
>

130
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<i class="fa fa-handshake fa-2x mr-3"></i>


<p class="text-left p-0">
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Dolorum
</p>
</div>
</div>
</div>
</section>
<!--======================Collection Section======================-->
<section class="container">
<div class="mt-3">
<div class="row justify-content-center">
{% for i in prod %}
<div class="col-lg-3 col-md-6 p-0">
<div class="card p-1 border-0 scale-style">
<a href=>
<img
class="card-img-top img-hover"
src={{i.image.url}}
alt="Card image cap"
style="height: 300px"
/>
</a>
<div class="card-body text-center">
<p class="card-text text-center">{{i.catname}}</p>
<a href={% url "deletepro" i.id %}>
<button type="button" class="btn btn-outline-danger mt-2">
Delete
</button>
</a>
<a href={% url "updatepro" i.id %}>
<button type="button" class="btn btn-outline-success mt-2">
Update
</button>
</a>
</div>
</div>
</div>
{% endfor %}

</div>
</div>
</section>
<!--======================Footer Section======================-->
<footer class="bg-dark text-light py-4">
<div class="container">
<div class="row">
<div class="col-md-4">
<h5>Contact Us</h5>
<p>Email: [email protected]</p>
<p>Phone: 123-456-7890</p>
</div>
<div class="col-md-4">
<h5>Links</h5>
<ul class="list-unstyled">

131
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<li><a href="#">Home</a></li>
<li><a href="#">Products</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
<div class="col-md-4">
<h5>Follow Us</h5>
<ul class="list-inline">
<li class="list-inline-item">
<a href="#"><i class="fab fa-facebook"></i></a>
</li>
<li class="list-inline-item">
<a href="#"><i class="fab fa-twitter"></i></a>
</li>
<li class="list-inline-item">
<a href="#"><i class="fab fa-instagram"></i></a>
</li>
</ul>
</div>
</div>
<hr />
<div class="row">
<div class="col text-center">
<p>&copy; 2023 Your E-Commerce Store</p>
</div>
</div>
</div>
</footer>
</body>
</html>
{% endblock abc %}

Task 36: Vendor Product Fetch


def venpro(request):
if 'vendoremail' in request.session:
b = vendor.objects.get(email = request.session['vendoremail'])
c = product.objects.filter(vendor = b.pk)
return render(request,'venpro.html',{'vensession':b,'prod':c})
else:
return redirect('venlogin')

132
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Task 37: Navigation


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"
/>
<title>E-commerce</title>
<link
rel="stylesheet"

href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-
Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
/>
<link
rel="stylesheet"

href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/
all.min.css"
integrity="sha512-
z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbb
KuqLg0DA=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/
GpGFF93hXpG5KkN"
crossorigin="anonymous"
></script>
<script

src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"

integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa
0b4Q"
crossorigin="anonymous"
></script>
<script

src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"

integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PV
CmYl"
crossorigin="anonymous"
></script>
<link rel="stylesheet" href="Style.css" />
</head>
<body>
<!--====================== Navbar ======================-->
<header class="container-fluid navbar-light bg-light">
<nav class="navbar container navbar-expand-lg navbar-light bg-

133
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

light">
<a class="navbar-brand" href="index.html">Navbar</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 ml-auto">
<li class="nav-item">
<a class="nav-link" href={% url "index" %}>Home</a>
</li>
{% if session %}
<li class="nav-item">
<a class="nav-link" href={% url "logout" %}>Logout</a>
</li>
<li class="nav-item">
<a class="nav-link" href="orderhistory.html">Order
History</a>
</li>
{% elif vensession %}
<li class="nav-item">
<a class="nav-link" href={% url "logout" %}>Logout</a>
</li>
<li class="nav-item">
<a class="nav-link" href={% url "addpro" %}>Start
selling..!</a>
</li>
<li class="nav-item">
<a class="nav-link" href={% url "soldpro" %}>Sold
Products</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href={% url "login" %}>User Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href={% url "venlogin" %}>vendor
Login</a>
</li>
{% endif %}
<li class="nav-item">
<a class="nav-link" href={% url "profile" %}>Profile</a>
</li>

<li class="nav-item">
<a class="nav-link" href="addproduct.html">
<i class="fa-solid fa-plus-square text-dark" aria-

134
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

hidden="true">
Add product</i
>
</a>
</li>
<li class="nav-item">
<input
class="input-group-text"
type="text"
placeholder="Search"
/>
</li>
<li class="nav-item">
<a class="nav-link" href={% url "cart" %}
><i class="fa fa-cart-shopping text-dark" aria-
hidden="true"></i
></a>
</li>
{% if session %}
<li class="nav-item">
<a class="nav-link" href="#">Welcome,{{session.name}}</a>
</li>
{% elif vensession %}
<li class="nav-item">
<a class="nav-link" href="#">Welcome,
{{vensession.name}}</a>
</li>
<li class="nav-item">
<a class="nav-link" href={% url "venpro" %}>My
products</a>
</li>
{% endif %}
</ul>
</div>
</nav>
</header>
<!-- content -->
{% block abc %}
{% endblock abc %}
</body>
</html>

Task 38: Generalized Form


<!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>
<form method="post">
{% csrf_token %}
<label for="">Enter name: </label>

135
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

<input type="text" name="uname">

<label for="">Enter text: </label>


<input type="text" name="data">

<button type="submit"> Submit </button>


</form>
</body>
</html>

Task 39: Payment Success Check

<h2>Payment Success.......</h2>

Task 40: Necessary Settings

INSTALLED_APPS = [
'jazzmin',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1',

Task 41: Define Encryption Key

import os
ENCRYPT_KEY = b'DJ3r34r9zSRPM8OWucrsv2PDBEA6BYaGpfJx67C9_us='

136
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

Task 42: Testing and Optimization

Write unit tests for each module and functionality.

# tests.py
from django.test import TestCase
from .models import Product

class ProductTestCase(TestCase):
def setUp(self):
Product.objects.create(name="Test Product", price=10.0,
description="Test Description")

def test_product_creation(self):
product = Product.objects.get(name="Test Product")
self.assertEqual(product.price, 10.0)

Task 43: Deployment


Set up hosting environment.

# Example: Heroku deployment


heroku create
git push heroku master
heroku open

Task 44: Documentation


Document codebase, APIs, and configurations.

## API Documentation

137
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django

### Products
- **GET /api/products**: Get all products
- **POST /api/products**: Create a new product

## Configuration
- **Database**: PostgreSQL
- **Payment Gateway**: Stripe

Task 45: Post-Deployment Support

 Monitor website performance and user feedback.


 Provide ongoing maintenance and support.

138
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT

You might also like