FinalTravel Diary
FinalTravel Diary
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
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.
2
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
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
4
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
Day 2
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”
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.
9
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
Day 4
“Memories”
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'})}
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.
11
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
Day 5
“Landing Page”
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
rel="stylesheet">
<link href="{% static 'assets/vendor/owl.carousel/assets/owl.carousel.min.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>
<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>
</div>
</nav>
<main id="main">
</div>
</div>
</div>
</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 -->
</div>
</div>
</footer>
</body>
</html>
16
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
Day 6
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”
<!—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">
18
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
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>
<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
</div>
</nav>
<main id="main">
</div>
<div class="row">
<div class="col-md-6 mb-5 mb-md-0" data-aos="fade-up">
<div class="row">
<div class="col-md-6 form-group">
<label for="name">Title</label>
</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
</form>
</div>
</div>
</div>
</section>
<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>
</body>
</html>
22
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
Day 8
“Create Work”
<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
23
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
<!-- =======================================================
* 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>
<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>
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>
</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="mb-5">
<p>
{{obj.desc}}
</p>
</div>
</div>
</div>
</div>
</div>
25
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
</section>
26
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
</body>
</html>
27
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
Day 9
“Work View”
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”
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
29
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
<!-- =======================================================
* 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>
30
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
</div>
</div>
</div>
</nav>
<main id="main">
31
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
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 -->
<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>— 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>— Chris Stanworth</p>
</div>
</div>
</div>
</div>
</section><!-- End Testimonials Section -->
33
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
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”
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.
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)
def __str__(self):
return self.name
class order(models.Model):
add = models.TextField()
pincode = models.CharField(max_length = 6)
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.
- `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.
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.
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:
2. Now, let's create a simple Flask application that demonstrates session-based navigation. We'll
have three pages: Home, About, and Contact.
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>
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.
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
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
@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
```
```python
# In wishlist/urls.py
48
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
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'),
]
```
```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 %}
```
7. **Include Wishlist URLs**: Include wishlist URLs in the main project's URL configuration.
```python
# In ecommerce_project/urls.py
49
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
urlpatterns = [
path('admin/', admin.site.urls),
path('wishlist/', include('wishlist.urls')),
]
```
```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:
```python
#In settings.py
DATABASES={
‘default’:{
‘ENGINE’:’django.db.backends.sqlite3’,
‘NAME’:’django.db.backends.sqlite3’,
}
}
’’’
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.
```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:
```bash
pip install mysqlclient
```
```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
}
}
```
```python
# In models.py
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
```
```bash
python manage.py makemigrations
python manage.py migrate
```
```python
# In views.py
54
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
def product_list(request):
products = Product.objects.all()
return render(request, 'product_list.html', {'products': products})
```
```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:
```bash
pip install razorpay
```
```python
# In settings.py
RAZORPAY_API_KEY = 'your_api_key'
RAZORPAY_API_SECRET = 'your_api_secret'
```
```html
<!-- In payment_form.html -->
56
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
```python
# In views.py
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')
```
```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
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:
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.
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.
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
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:
```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.
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
64
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
)
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:
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
======================-->
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">
73
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
74
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
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/">
76
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
<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
</style>
<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>
80
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
<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">
82
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
<h4 class="mb-3">Payment</h4>
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>
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
======================-->
<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
90
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
Day 24
“Deployment”
91
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
92
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
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
# 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()
# 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})
# views.py
from .models import Product
from django.shortcuts import render, get_object_or_404
# 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
# views.py
def checkout(request):
if request.method == 'POST':
# Handle payment processing
return redirect('order_confirmation')
return render(request, 'checkout.html')
# views.py
def profile(request):
user = request.user
orders = Order.objects.filter(user=user)
return render(request, 'profile.html', {'user': user, 'orders': orders})
# 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)
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
class App1Config(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'app1'
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'),
STATIC_URL = '/static/'
import os
MEDIA_ROOT = os.path.join(BASE_DIR,'media/img/')
MEDIA_URL = '/media/img/'
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
class category(models.Model):
catname = models.CharField(max_length=50)
image = models.ImageField(upload_to='imgcat')
def __str__(self):
return self.catname
124
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
else:
return render(request,'otp.html')
125
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
else:
a = product.objects.get(id = id)
return render(request,'updatepro.html',{'proupdatedetail':a})
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')
// Your/store name.
name: "morning E-commerce",
</script>
</body>
</html>
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
</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>© 2023 Your E-Commerce Store</p>
</div>
</div>
</div>
</footer>
</body>
</html>
{% endblock abc %}
132
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
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>
<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>
135
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
<h2>Payment Success.......</h2>
INSTALLED_APPS = [
'jazzmin',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1',
import os
ENCRYPT_KEY = b'DJ3r34r9zSRPM8OWucrsv2PDBEA6BYaGpfJx67C9_us='
136
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT
Python with django
# 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)
## 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
138
VPMP POLYTECHNIC (654), COMPUTER DEPARTMENT