Blood Test System
Blood Test System
When coupled with the Django framework, Python becomes even more
formidable for web development. Django, a high-level web framework,
streamlines the creation of robust, scalable web applications. Built on the
principles of DRY (Don't Repeat Yourself) and convention over configuration,
Django promotes clean, maintainable code and accelerates development through
its built-in features and utilities.
[Python Functionality]
- Clear Syntax
- Extensive Standard Library
- Dynamic Typing
- Support for Multiple Programming Paradigms
- Object-Oriented
- Functional
- Procedural
[Django Framework]
[Web Applications]
- Robust
- Scalable
- Secure
- Efficiently Developed
Prompt: Compare python with other programming languages
Day 2
1. **Setup Environment:**
- Install Django: `pip install django`.
- Create a new Django project: `django-admin startproject myproject`.
- Create a new app: `python manage.py startapp myapp`.
2. **Define Models:**
```python
# myapp/models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
```
3. **Migrate Database:**
```
python manage.py makemigrations
python manage.py migrate
```
4. **Create Views:**
```python
# myapp/views.py
from django.shortcuts import render
from .models import MyModel
def my_view(request):
objects = MyModel.objects.all()
return render(request, 'myapp/my_template.html', {'objects': objects})
```
5. **Create Templates:**
- Create `my_template.html` in `myapp/templates/myapp/` directory.
6. **Define URLs:**
```python
# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.my_view, name='my_view'),
]
```
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
```
This is a basic setup to get you started. From here, you can expand your project by adding more
models, views, templates, and functionalities as needed.
Day 3
Step 1: Go to ‘views.py’ location and write code for login and signup.
def Lab_signin(request):
if request.method=="POST":
print(request.POST['Lid'])
try:
m = LaboratoryRegister.objects.get(Lid=request.POST['Lid'])
if m.Laboratorypwd == request.POST['Laboratorypwd']:
request.session['Lid'] = m.Lid
request.session['name'] = m.Laboratoryfname
request.session['fname'] = m.Laboratorymname
request.session['mname'] = m.Laboratorylname
return redirect('laboratory:index')
else:
return render(request,'Lab_signin.html',{'m':'Password incorrect'})
except:
return render(request,'Lab_signin.html',{'m':'Password incorrect'})
return render(request,'Lab_signin.html')
def signin(request):
if request.POST:
email = request.POST['uid']
pass1 = request.POST['userpwd']
try:
valid = UserRegister.objects.get(uid=email,userpwd=pass1)
if valid:
request.session['user'] = email
request.session['userId'] = valid.pk
return redirect('user:index')
else:
return render(request,'signin1.html',{'m':'Password incorrect'})
except:
return render(request,'signin1.html',{'m':'Password incorrect'})
# return redirect('/signin/')
return render(request,'signin1.html')
# Registration
def signup(request):
obj=UserRegisterForm(request.POST)
if obj.is_valid():
data=UserRegister.objects.all().filter(uid=request.POST['uid'])
if len(data)<=0:
obj.save()
return redirect('user:signin')
else:
return render(request,'signup.html',{'messagekey':"User Already Exists"})
return render(request,'signup.html')
def Lab_signup(request):
obj=LaboratoryRegisterform(request.POST,request.FILES)
if obj.is_valid():
data=LaboratoryRegister.objects.all().filter(Lid=request.POST['Lid'])
print(len(data))
if len(data)<=0:
obj.save()
return redirect('laboratory:lab_signin')
else:
return render(request,'Lab_signup.html',{'messagekey':"User Already Exists"})
return render(request,'Lab_signup.html')
{% load static%}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>َLogin</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="{% static 'signin1.css' %}">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></
script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></
script>
<style>
.card{
background-color: transparent;
color: #017f92;
}
a{
color: #017f92;
}
a:hover{
color: #017f92;
}
</style>
</head>
<body>
<div>
<img src="{% static 'img/bg20.jpg' %}" style="height: 100vh; width:100%;
position:absolute; z-index: -1; opacity: 1;">
</div>
<div style="position:relative; top:100px;">
<center>
<div class="col-md-4">
<div class="card bg-mute">
<form method="POST" autocomplete="off">
{% csrf_token %}
<h1 class="h1 text-center mt-5 mb-5">Laboratory Login</h1>
<div class="m-1">
<input type="email" class="form-control" id="email" placeholder="Enter email"
name="Lid" value="{{ Lid }}">
</div>
<div class="m-1">
<input type="password" class="form-control" placeholder="Enter password"
name="Laboratorypwd" value="{{ Laboratorypwd }}">
</div>
<div class="mt-1 mb-1">
<a href="/med/show/"><button type="submit" class="btn btn-info">Sign
Up</button></a>
</div>
<hr/>
<div class="foot-lnk text-center">
<a href="{% url 'laboratory:lab_signup' %}">Create an account</a>
</div>
</form>
</div>
</div>
</center>
</div>
{% if m %}
<script>alert("{{m}}")</script>
{% endif %}
</body>
</html>
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>َLogin</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="{% static 'signin1.css' %}">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></
script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></
script>
<style>
.card{
background-color: transparent;
color: #17a2b8;
}
a{
color: #17a2b8;
}
a:hover{
color: #17a2b8;
}
</style>
</head>
<body>
<div>
<img src="{% static 'img/login.jpg' %}" style="height: 100vh; width:100%;
position:absolute; opacity: 0.5;">
</div>
<div style="position:relative; top:100px;">
<center>
<div class="col-md-4">
<div class="card">
<form method="POST" >
{% csrf_token %}
<h1 class="h1 text-center mt-5 mb-5">User Login</h1>
<div class="m-1">
<input type="text" class="form-control" id="email" placeholder="Enter email"
name="uid" value="{{ uid }}">
</div>
<div class="m-1">
<input type="password" class="form-control" placeholder="Enter password"
name="userpwd" value="{{ userpwd }}">
</div>
<div class="mt-4 mb-3">
<div class="">
<button type="submit" class="btn btn-info">Sign In</button>
</div>
</div>
<hr/>
</form>
</div>
</div>
</center>
</div>
{% if m %}
<script>alert("{{m}}")</script>
{% endif %}
</body>
</html>
<!—register.html -->
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>Registration</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="{% static 'signin1.css' %}">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></
script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></
script>
<style>
.card{
background-color: transparent;
color: #17a2b8;
}
a{
color: #17a2b8;
}
a:hover{
color: #17a2b8;
}
</style>
</head>
<body>
<div>
<img src="{% static 'img/login.jpg' %}" style="height: 100vh; width:100%;
position:absolute; opacity: 0.5;">
</div>
<div style="position:relative;">
<center>
<div class="col-md-4">
<div class="card">
<form method="POST" >
{% csrf_token %}
<div class="m-1">
<input type="email" class="form-control" id="email"
placeholder="Enter email"name="uid" value="{{ uid }}" >
</div>
<div class="m-1">
<input type="password" class="form-control"
placeholder="Enter password" name="userpwd" value="{{ userpwd }}">
</div>
<div class="m-1">
<input type="text" class="form-control" id="fname"
placeholder="First Name" name="userfname" value="{{ userfname }}">
</div>
<div class="m-1">
<input type="text" class="form-control" id="mname"
placeholder="Middle Name" name="usermname" value="{{ usermname }}">
</div>
<div class="m-1">
<input type="text" class="form-control" id="lname"
placeholder="Last Name" name="userlname" value="{{ userlname }}">
</div>
<div class="m-1">
<input type="number" class="form-control"
id="user_age" placeholder="Age" name="user_age" value="{{ user_age }}">
</div>
<label class="m-1" for="gender"> Select your gender</label>
<select name="usergender" class="m-1">
<option value="none" selected>Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<div class="m-1">
<textarea row="3" class="form-control" id="Address"
placeholder="Address" name="useraddress" value="{{ useraddress }}"></textarea>
</div>
<div class="m-1">
<input type="text" class="form-control" id="city"
placeholder="City" name="usercity" value="{{ usercity }}">
</div>
<div class="m-1">
<input type="text" class="form-control" id="area"
placeholder="Area" name="userarea" value="{{ userarea }}">
</div>
<div class="m-1">
<input type="text" class="form-control" id="Pincode"
placeholder="Pincode" name="userpincode" value="{{ userpincode }}">
</div>
<div class="m-1">
<input type="number" class="form-control"
id="content_no" placeholder="Contact No" name="usercontactno"
value="{{ usercontactno }}">
</div>
<div class="mt-1 mb-1">
<button type="submit" class="btn btn-info">Sign
Up</button>
</div>
<hr/>
<div class="foot-lnk text-center">
<a href="{% url 'user:signin' %}">Already Member?</a>
</div>
</form>
</div>
</div>
</center>
{% if messagekey %}
<script>alert("{{ messagekey }}")</script>
{% endif %}
</div>
</body>
</html>
{% load static%}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>َLogin</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="{% static 'signin1.css' %}">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></
script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></
script>
<style>
.card{
background-color: transparent;
color: #017f92;
}
a{
color: #017f92;
}
a:hover{
color: #017f92;
}
</style>
</head>
<body>
<div>
<img src="{% static 'img/lab.jpg' %}" style="height: 100vh; width:100%; position:absolute;
z-index: -1; opacity: 0.5;">
</div>
<div style="position:relative;">
<center>
<div class="col-md-4">
<div class="card">
<form method="POST" autocomplete="off" enctype="multipart/form-data">
{% csrf_token %}
<h1 class="h1 text-center mt-2 mb-2">Laboratory Signup</h1>
<div class="">
<input type="email" class="form-control" id="email" placeholder="Enter email"
name="Lid" value="{{ Lid }}">
</div>
<div class="">
<input type="password" class="form-control" placeholder="Enter password"
name="Laboratorypwd" value="{{ Laboratorypwd }}">
</div>
<div class="">
<input type="text" class="form-control" id="fname" placeholder="Laboratory
Name" name="Laboratoryfname" value="{{ Laboratoryfname }}">
</div>
<div class="">
<input type="text" class="form-control" id="mname" placeholder="First Name"
name="Laboratorymname" value="{{ Laboratorymname }}">
</div>
<div class="">
<input type="text" class="form-control" id="lname" placeholder="Last Name"
name="Laboratorylname" value="{{ Laboratorylname }}">
</div>
<div class="">
<textarea row="2" class="form-control" id="Address" placeholder="Address"
name="Laboratoryaddress" value="{{ Laboratoryaddress }}"></textarea>
</div>
<div class="">
<input type="text" class="form-control" id="city" placeholder="City"
name="Laboratorycity" value="{{ Laboratorycity }}">
</div>
<div class="">
<input type="text" class="form-control" id="area" placeholder="Area"
name="Laboratoryarea" value="{{ Laboratoryarea }}">
</div>
<div class="">
<input type="text" class="form-control" id="Pincode" placeholder="Pincode"
name="Laboratorypincode" value="{{ Laboratorypincode }}">
</div>
<div class="">
<input type="number" class="form-control" id="content_no"
placeholder="Contact No" name="Laboratorycontactno" value="{{ Laboratorycontactno }}">
</div>
<div class="">
<input id="id_chemistphoto" type="file" name="Laboratoryphoto" class="form-
control" value="{{ Laboratoryphoto }}">
</div>
<div class="mt-2">
<a href="/med/show/"><button type="submit" class="btn btn-info">Sign
Up</button></a>
</div>
{% if messagekey %}
<script>alert("{{ messagekey }}")</script>
{% endif %}
<hr/>
<div class="foot-lnk text-center">
<a href="{% url 'laboratory:lab_signin' %}">Already Member?</a>
</div>
</form>
</div>
</div>
</center>
</div>
</body>
</html>
class LaboratoryRegisterform(forms.ModelForm):
class Meta:
model=LaboratoryRegister
fields='__all__'
class UserRegisterForm(forms.ModelForm):
class Meta:
model=UserRegister
fields='__all__'
# User Details
class UserRegister(models.Model):
uid=models.EmailField(max_length=50,verbose_name='Email')
userpwd=models.CharField(max_length=20,verbose_name='Password')
userfname=models.CharField(max_length=20,default='',verbose_name='First_Name')
usermname=models.CharField(max_length=20,default='',verbose_name='Middle_Name'
)
userlname=models.CharField(max_length=20,default='',verbose_name='Last_Name')
n='slect gender'
g=[
(None, 'select gender'),
('Male', 'Male'),
('Female', 'Female'),
]
usergender=models.CharField(max_length=12,choices=g,default=None)
user_age=models.IntegerField(max_length=3,default=None)
useraddress=models.CharField(max_length=20,default='',verbose_name='Address')
usercity=models.CharField(max_length=30,default='',verbose_name='City')
userarea=models.CharField(max_length=20,default='',verbose_name='Area')
userpincode=models.IntegerField(default='',verbose_name='Pincode')
usercontactno=models.IntegerField(default='',verbose_name='Contact_No')
def __str__(self):
return self.uid
class LaboratoryRegister(models.Model):
Lid=models.EmailField(max_length=50,verbose_name='Email')
Laboratorypwd=models.CharField(max_length=20,verbose_name='Password')
Laboratoryfname=models.CharField(max_length=20,default='',verbose_name='Laborator
y_Name')
Laboratorymname=models.CharField(max_length=20,default='',verbose_name='First_Na
me')
Laboratorylname=models.CharField(max_length=20,default='',verbose_name='Last_Nam
e')
Laboratoryaddress=models.CharField(max_length=20,default='',verbose_name='Address'
)
Laboratorycity=models.CharField(max_length=20,default='',verbose_name='City')
Laboratoryarea=models.CharField(max_length=20,default='',verbose_name='Area')
Laboratorypincode=models.IntegerField(default='',verbose_name='Pincode')
Laboratorycontactno=models.IntegerField(default='',verbose_name='Contact_No')
Laboratoryphoto = models.FileField(upload_to = 'upload',verbose_name='Laboratory
certificate')
def __str__(self):
return self.Lid
Day 4
“Dashboard”
def lab_home(request):
if 'Lid' in request.session:
a=LaboratoryRegister.objects.get(Lid=request.session['Lid'])
b=Test_category.objects.all()
return render(request,'index.html',{'a':a,'b':b,'c':len(b)})
else:
return redirect('laboratory:lab_signin')
def index(request):
if 'user' in request.session.keys():
b=UserRegister.objects.get(id=request.session['userId'])
x=Test_category.objects.filter(email=request.session['user'])
return render(request,'index1.html',{'b':b,'x':x})
return redirect('user:signin')
<!—index.html -->
{% extends 'admin_base.html' %}
{% load static %}
{% block content %}
<h1 class="text-center mb-2" style="font-family: 'Adamina';font-size: 40px; color:rgba(255,
165, 0, 1); ">
Welcome {{ a.Laboratorymname}}
</h1>
<div class="dashboard">
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="row m-5">
<div class="col-md-8">
{% comment %} <img src="{% static 'icon/test.png' %}" class="fafa"
height="50px" width="50px"><br> {% endcomment %}
<span class="text-muted">Total Patient Test Report</span>
</div>
<div class="col-md-4">
<span class="ts" style="font-weight: 900; font-size: 25px;">{{ c }}</span>
</div>
</div>
</div>
</div>
</div>
<div class="card" style="margin-top:100px; padding:0px 10px 0px 10px ;">
<div class="baner" style="margin: auto; margin-top:-4%; margin-bottom:20px;">
<h3 class="text-center" style="font-weight: bold; padding: 10px 0px 10px 0px;">
Patient Records Report</h3>
</div>
<table class="table table-hover table-striped" id="myTable">
<thead>
<tr>
<th>No</th>
<th>Patient NAME</th>
<th>Patient Email</th>
<th>Test Name</th>
<th>Haemoglobin</th>
<th>Platelet_Count</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for i in b %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{ i.patientname }}</td>
<td>{{ i.email }}</td>
<td>{{ i.Test_name }}</td>
<td>{{ i.Haemoglobin }}</td>
<td>{{ i.Platelet_Count }}</td>
<td>{{ i.date_of_test }}</td>
<td>
<a href="{% url 'laboratory:view_test' i.id %}">view</a>
<a href="{% url 'laboratory:delete_test' i.id %}"><img src="{% static
'icon/delete.png' %}" height="30px"
width="30px"></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
<!—index1.html -->
{% extends 'user_base.html' %}
{% load static %}
{% block content %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
Step 3: ‘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.
urlpatterns = [
# signin,signup,indexpage
path('',Lab_signin,name="lab_signin"),
path('signup/',Lab_signup,name="lab_signup"),
path('lab/',lab_home,name="index"),
#profile
path('lab_profile/',lab_profile,name="lab_profile"),
#Logout
path('logout/',logout,name='logout'),
#add category
path('add_category/',add_category,name='add_category'),
#view category
path('view_category/',view_category,name='view_category'),
#edit category
path('edit_category/<int:id>/',edit_category,name='edit_category'),
path('delete_category/<int:id>/',delete_category,name='del_category'),
#appointment show
path('show_appointment/',show_appo,name='show_appointment'),
# reject appointment
# path('delete_test/<int:id>',delete_appointment,name='delete_appo'),
#book appointment
path('edit/<int:id>/',edit_appo,name="edit_appo"),
# show approved appointment
#book appointment
path('show_test',view_approvedappo,name="view_approvedappo"),
#take test
path('take_test/<int:id>/',take_test,name='take_test'),
#view test
path('view_test/<int:id>/',view_test,name='view_test'),
path('delete_test/<int:id>/',delete_test,name='delete_test'),
path('read_feedback/',view_feedback,name='view_feedback'),
path('read_feedback/<int:id>/',show_feedback,name='show_feedback'),
]
from django.urls import path
from patientapp.views import *
urlpatterns = [
#User Signin,Signup,Logout,IndexpagenIndexpage1
path('',signin,name="signin"),
path('index/',index,name="index"),
path('signup/',signup,name="signup"),
path('logout/',logout,name='logout'),
path('book_appointment/',book_appointment,name="book_appointment"),
path('view_test/<int:id>',view_test,name='view_test'),
path('view_appointment_status/',view_appo_status,name="view_approvedappo"),
path('delete_appo/<int:id>',delete_appointment,name='delete_appointment'),
path('send_feedback/',user_feedback,name='user_feedback'),
path('user_profile/',user_profile,name='user_profile'),
# path('Generatedpdf/<int:id>',GeneratePdf,name="pdf"),
]
Day 5
“Patient Details”
def view_test(request,id):
if 'user' in request.session.keys():
b=Test_category.objects.get(pk=id)
c=UserRegister.objects.get(uid=b.email)
return render(request,'datatable.html',{'b':b,'c':c})
else:
return redirect('user:signin')
{% extends 'admin_base.html' %}
{% load static %}
{% block content %}
<div class="dashboard">
<div class="card" style="margin-top:100px; padding:0px 10px 0px 10px ;">
<div class="baner" style="margin: auto; margin-top:-4%; margin-bottom:20px;">
<h3 class="text-center" style="font-weight: bold; padding: 10px 0px 10px 0px;">
Patient Approved Records</h3>
</div>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for x in b %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{x.name}}</td>
<td>{{x.phone}}</td>
<td>{{x.email}}</td>
<td>{{x.schedule}}</td>
<td>{{x.Test_name}}</td>
<td><a class="btn btn-danger" href="{% url 'laboratory:take_test' x.id
%}">Test</a></td>
</tr>
{% endfor %}
</tbody>
</tbody>
</table>
</div>
</div>
{% endblock %}
# models.py
class Test_category(models.Model):
l_name=models.CharField(max_length=200,default='',verbose_name='Lab Assistance
Name')
lab_name=models.CharField(max_length=200,default='',verbose_name='Lab Name')
Test_name=models.CharField(max_length=200,default='',verbose_name='Blood Test
Name')
patientname=models.CharField(max_length=200,default='',verbose_name='Patient Name')
email = models.EmailField(default="")
Haemoglobin=models.PositiveIntegerField(default="")
RBC_Count=models.PositiveIntegerField(default="")
PCV=models.PositiveIntegerField(default="")
MCV=models.PositiveIntegerField(default="")
MCH=models.PositiveIntegerField(default="")
MCHC=models.PositiveIntegerField(default="")
RDW=models.PositiveIntegerField(default="")
Total_WBC_Count=models.PositiveIntegerField(default="")
Neutrophils=models.PositiveIntegerField(default="")
Lymphocytes=models.PositiveIntegerField(default="")
Eosinophils=models.PositiveIntegerField(default="")
Monocytes=models.PositiveIntegerField(default="")
Basophils=models.PositiveIntegerField(default="")
Platelet_Count =models.PositiveIntegerField(default="")
WBCs_on_PS=models.CharField(max_length=50,default="")
date_of_test=models.DateField(auto_created=True,auto_now=True)
def __str__(self):
return str(self.Test_name)
class Reference_Test_category(models.Model):
Haemoglobin_reference = models.TextField(default="male : 14 - 16g \n Female : 12 - 14 g")
RBC_reference = models.TextField(default="14 - 16g%")
PCV_reference = models.TextField(default="35 - 45 %")
MCV_reference = models.TextField(default="80 - 99 fl")
MCH_reference = models.TextField(default="28 - 32 pg")
MCHC_reference = models.TextField(default="30 - 34 %")
RDW_reference = models.TextField(default="9 - 17 fl")
Total_WBC_Count_reference = models.TextField(default="4000 - 11000 / cu.mm")
Neutrophils_reference = models.TextField(default="40 - 75 %")
Lymphocytes_reference = models.TextField(default="20 - 45 %")
Eosinophils_reference = models.TextField(default="00 - 06 %")
Monocytes_reference = models.TextField(default="00 - 10 %")
Basophils_reference = models.TextField(default="00 - 01 %")
Platelet_Count_reference = models.TextField(default="150000 - 450000 / cu.mm")
def __str__(self):
return str(self.Test_name)
Step 4: Migrate Models, after defining models, run the `makemigrations` and `migrate`
commands to create corresponding database tables based on the model definitions.
“Feedbacks”
def user_feedback(request):
if 'user' in request.session.keys():
c=UserRegister.objects.get(id=request.session['userId'])
print(c)
if request.POST:
name=request.POST['name']
email=request.POST['email']
Feedback=request.POST['Feedback']
a=Userfeedback()
a.username=name
a.useremail=email
a.feedback=Feedback
a.save()
return redirect('user:index')
return render(request,'user_feedback.html',{'n':c})
else:
return redirect('user:signin')
def view_feedback(request):
if 'Lid' in request.session:
obj=Userfeedback.objects.all()
return render(request,'view_feedback.html',{'b':obj})
return redirect('laboratory:lab_signin')
def show_feedback(request,id):
if 'Lid' in request.session:
obj=Userfeedback.objects.get(id=id)
return render(request,'show_feedback.html',{'b':obj})
return redirect('laboratory:lab_signin')
<!—user_feedback.html -->
{% extends 'user_base.html' %}
{% load static %}
{% block content %}
<div></div>
<div class="dashboard">
<div class="card" style="margin-top:100px; padding:0px 10px 0px 10px ;">
<div class="baner" style="margin: auto; margin-top:-4%; margin-bottom:20px;">
<h3 class="text-center" style="font-weight: bold; padding: 10px 0px 10px 0px;">
Feedback</h3>
</div>
<form method="post" class="col-8 mt-5" style="margin:auto;">
{% csrf_token%}
<div class="form-group">
<label>Patient name</label>
<input type="text" placeholder="Enter name" class="form-control" name="name"
value="{{n.userfname}}" readonly>
</div>
<div class="form-group">
<label>Patient email</label>
<input type="email" placeholder="Enter email" class="form-control" name="email"
value="{{n.uid}}" readonly>
</div>
<div class="form-group">
<label>write Feedback</label>
<textarea type="text" placeholder="Enter password" class="form-control"
name="Feedback" required></textarea>
</div>
<br>
<input type="submit" class="btn btn-block" value="submit" />
</form>
</br>
</div>
</div>
{% endblock %}
<!—view_feedback.html
{% extends 'admin_base.html' %}
{% load static %}
{% block content %}
<div class="dashboard">
<td>
<a href="{% url 'laboratory:show_feedback' i.id %}">view</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
<!—show_feedback.html
{% extends 'admin_base.html' %}
{% load static %}
{% block content %}
<div></div>
<div class="dashboard">
<div class="card" style="margin-top:100px; padding:0px 10px 0px 10px ;">
<div class="baner" style="margin: auto; margin-top:-4%; margin-bottom:20px;">
<h3 class="text-center" style="font-weight: bold; padding: 10px 0px 10px 0px;">
Feedback</h3>
</div>
<form method="post" class="col-8 mt-5" style="margin:auto;">
{% csrf_token%}
<div class="form-group">
<label>Patient name</label>
<input type="text" class="form-control" name="name"
value="{{b.username}}" readonly>
</div>
<div class="form-group">
<label>Patient email</label>
<input type="email" class="form-control" name="email"
value="{{b.useremail}}" readonly>
</div>
<div class="form-group">
<label>write Feedback</label>
<textarea type="text" placeholder="Enter password" class="form-control"
required>{{b.feedback}}</textarea>
</div>
<br>
</form>
</br>
</div>
</div>
{% endblock %}
# app1 /models.py
class Userfeedback(models.Model):
username=models.CharField(max_length=30,default='',verbose_name='Patient Name')
useremail=models.EmailField(max_length=50,verbose_name='Patient Email')
feedback=models.TextField(verbose_name='Patient feedback Area')
date_of_feedback=models.DateField(auto_created=True,auto_now=True)
def __str__(self):
return self.username
Step 4: Migrate Models, after defining models, run the `makemigrations` and `migrate`
commands to create corresponding database tables based on the model definitions.
“Patient Appointments”
import datetime
from django.utils.dateparse import parse_datetime
def book_appointment(request):
if 'user' in request.session.keys():
a=Name_category.objects.all()
b=UserRegister.objects.get(id=request.session['userId'])
form = appointmentform(request.POST)
#print(form)
if form.is_valid():
c=Appointment.objects.filter(email=request.POST['email']) &
Appointment.objects.filter(status='pending')
if len(c)<=0:
cDate = datetime.datetime.today()
postDate = request.POST['schedule']
postDateArray = postDate.split("T")
cDateArray = str(cDate).split(" ")
if parse_datetime(postDateArray[0]) >= parse_datetime(cDateArray[0]):
form.save()
messages.success(request,'Your appoinement is booked.')
else:
return render(request,'book_appointment.html',
{'form':form,'ab':a,'b':b,'m':'select future date only'})
else:
return render(request,'book_appointment.html',
{'form':form,'ab':a,'b':b,'m':'appointment alredy booked'})
return render(request,'book_appointment.html',{'form':form,'ab':a,'b':b})
return redirect('user:signin')
def view_appo_status(request):
if 'user' in request.session.keys():
b=Appointment.objects.filter(email=request.session['user'])
return render(request,'view_appointment.html',{'b':b})
else:
return redirect('user:signin')
def delete_appointment(request,id):
if 'user' in request.session.keys():
obj=Appointment.objects.get(pk=id)
obj.delete()
return redirect('user:view_approvedappo')
return redirect('user:signin')
<!—book_appointment..html -->
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Book_appoinement</title>
<!-- <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> -->
<style>
body{
margin: 0;
padding: 300px;
background: #34495e;
background-size: 100%;
background-position: 100%;
font-family: sans-serif;
}
body{
margin: 0;
padding: 0;
font-family: sans-serif;
background: #34495e;
}
.book-appoinement{
width: 1px;
height: 470px;
background: black;
color: #fff;
top: 50%;
left: 50%;
position: absolute;
transform: translate(-50%,-50%);
box-sizing: border-box;
padding: 70px 30px;
}
.book-appoinement select[id="id_department"]{
background-color: transparent;
color: white;
padding-right: 5%;
}
.button {
background-color: #4c90af;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 19px;
}
.time {
background-color: #6f7a6f81; /* Green */
border: none;
color: white;
margin-right: 10%;
/* text-align: center; */
text-decoration: none;
/* display: inline-block; */
font-size: 16px;
}
option{
color: rgb(48, 47, 47);
font-size: larger;
}
.box{
width: 300px;
padding: 40px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: #191919;
text-align: center;
}
</style>
</head>
<body>
<div class="book-appoinement">
<center>
<!-- style="padding-top: 250px;
font-size: x-large;" -->
<form method="POST" class="box">
{% csrf_token %}
<div>
<h1>Book AppointMent</h1>
<label>Name:</label>
<input type="text" name="name" value="{{b.userfname}}" readonly>
</div>
<br>
<div class="row">
<div>
<label>Email:</label>
<input type="email" name="email" value="{{b.uid}}" readonly >
</div></div>
<br>
<div>
<label>Phone:</label>
<input type="text" name="phone" placeholder="Enter phone number"
value="{{b.usercontactno}}" readonly>
</div>
<br>
<div class="d-department">
<label for="id_department">Test Name:</label>
</div>
<br>
<div>
<label>Schedule:</label>
<input type="datetime-local" name="schedule" class="time">
</div>
<br>
<input type="hidden" name="status" placeholder="status" value="pending" readonly>
{% if messages %}
{% for result in messages %}
<center> <b style=color:green;>{{result}}</b></center>
{% endfor %}
{% endif %}
<br>
class Appointment(models.Model):
g=(
('pending', 'pending'),
('approved', 'approved'),
('rejected', 'rejected'),
)
name = models.CharField(max_length=500)
phone = models.IntegerField()
email = models.EmailField(max_length=100)
schedule = models.DateTimeField()
Test_name=models.ForeignKey(Name_category, on_delete=models.CASCADE)
status = models.CharField(max_length=12, choices=g, default = 'pending')
appointment_booked=models.BooleanField(default=False)
def __str__(self):
return self.name
Step 4: Migrate Models, after defining models, run the `makemigrations` and `migrate`
commands to create corresponding database tables based on the model definitions.
“Status Details”
def show_appo(request):
results=Appointment.objects.filter(status='pending')
return render(request,'show_appointment.html',{'book':results})
#book appointment
def edit_appo(request,id):
if 'Lid' in request.session.keys():
a=LaboratoryRegister.objects.get(Lid=request.session['Lid'])
book=Appointment.objects.get(pk=id)
if request.POST:
book.status=request.POST['boked']
book.save()
return redirect('laboratory:show_appointment')
return render(request,'edit_appointment.html',{'book':book,'owner_data':a})
else:
return redirect('laboratory:lab_signin')
def view_approvedappo(request):
if 'Lid' in request.session:
b=Appointment.objects.filter(status='approved') &
Appointment.objects.filter(appointment_booked=False)
return render(request,'take_bloodtest.html',{'b':b})
else:
return redirect('laboratory:lab_signin')
Step 2: Create template “edit_appointment.html” for BTS.
{% extends 'admin_base.html' %}
{% load static %}
{% block content %}
<!--/header-->
<section class="container">
<div class="row justify-content-center p-4">
<div class="col-12 col-md-6 p-5 card">
<h3 class="text-uppercase font-weight-bold text-center">Appointment Edit</h3>
<form method="POST" enctype="multipart/form-data" >
{% csrf_token %}
<br />
<div class="form-group row">
<label for="staticName" class="col-4 col-form-label">Patient Name</label>
<div class="col-auto">
<input type="text" readonly class="form-control" id="staticName"
value="{{ book.name }}" />
</div>
</div>
<div class="form-group row">
<label for="staticOwner" class="col-4 col-form-label">Phone</label>
<div class="col-auto">
<input
type="text"
readonly
class="form-control"
id="staticOwner"
value="{{ book.phone }}"
/>
</div>
</div>
<div class="form-group row">
<label for="staticProperty" class="col-4 col-form-label"
>Email</label
>
<div class="col-auto">
<input
type="text"
readonly
class="form-control"
id="staticProperty"
value="{{ book.email }}"
/>
</div>
</div>
<div class="form-group row">
<label for="staticName" class="col-4 col-form-label">Schedule</label>
<div class="col-auto">
<input type="text" readonly class="form-control" id="staticName"
value="{{ book.schedule }}" />
</div>
</div>
<div class="form-group row">
<label for="staticName" class="col-4 col-form-label">Test type</label>
<div class="col-auto">
<input type="text" readonly class="form-control" id="staticName"
value="{{ book.Test_name }}" />
</div>
</div>
<div class="form-group row">
<label
class="col-auto col-form-label d-inline-block"
for="customCheck1"
>Want to Approve:</label
>
<div class="col-7">
<select class="form-control w-100 text-center" id="boked" name="boked">
<option value="none" selected>select</option>
{% comment %} <option value="pending">pending</option> {% endcomment %}
<option value="approved">Approve</option>
<option value="rejected">Reject</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="col-12">
<input type="submit" value="submit" class="btn btn-primary btn-block" />
</div>
</div>
</form>
</div>
</div>
</section>
“Profile”
def lab_profile(request):
if 'Lid' in request.session:
a=LaboratoryRegister.objects.get(Lid=request.session['Lid'])
if request.POST:
name=request.POST['name']
email=request.POST['email']
password=request.POST['passowrd']
a.Laboratoryfname=name
a.Lid=email
a.Laboratorypwd=password
a.save()
return redirect('laboratory:index')
return render(request,'lab_profile.html',{'n':a})
else:
return redirect('laboratory:lab_signin')
def user_profile(request):
if 'user' in request.session.keys():
a=UserRegister.objects.get(id=request.session['userId'])
if request.POST:
name=request.POST['name']
email=request.POST['email']
password=request.POST['passowrd']
a.userfname=name
a.uid=email
a.userpwd=password
a.save()
return redirect('user:index')
return render(request,'user_profile.html',{'n':a})
else:
return redirect('user:signin')
{% extends 'admin_base.html' %}
{% load static %}
{% block content %}
<div></div>
<div class="dashboard">
<div class="card" style="margin-top:100px; padding:0px 10px 0px 10px ;">
<div class="baner" style="margin: auto; margin-top:-4%; margin-bottom:20px;">
<h3 class="text-center" style="font-weight: bold; padding: 10px 0px 10px 0px;"> Edit
Laboratory Profile</h3>
</div>
<form method="post" class="col-8 mt-5" style="margin:auto;">
{% csrf_token%}
<div class="form-group">
<label>Enter name</label>
<input type="text" placeholder="Enter name" class="form-control" name="name"
value="{{n.Laboratoryfname}}" required>
</div>
<div class="form-group">
<label>Enter email</label>
<input type="email" placeholder="Enter email" class="form-control" name="email"
value="{{n.Lid}}" readonly>
</div>
<div class="form-group">
<label>Enter password</label>
<input type="password" placeholder="Enter password" class="form-control"
name="passowrd" value="{{n.Laboratorypwd}}" required>
</div>
<br>
<input type="submit" class="btn btn-block" value="submit" />
</form>
</br>
</div>
</div>
{% endblock %}
Day 10
“Test Reports”
def take_test(request,id):
if 'Lid' in request.session:
a=request.session['fname']
c=request.session['name']
b=Appointment.objects.get(pk=id)
form =Testform(request.POST)
if form.is_valid():
b.appointment_booked=request.POST['test']
form.save()
b.save()
return redirect('laboratory:index')
return render(request,'bloodtest.html',{'a':a,'b':b,'c':c})
else:
return redirect('laboratory:lab_signin')
def view_test(request,id):
if 'user' in request.session.keys():
b=Test_category.objects.get(pk=id)
c=UserRegister.objects.get(uid=b.email)
return render(request,'datatable.html',{'b':b,'c':c})
else:
return redirect('user:signin')
Step 2: Go to ‘models.py’ location and build model.
# models.py
class Reference_Test_category(models.Model):
Haemoglobin_reference = models.TextField(default="male : 14 - 16g \n Female : 12 - 14 g")
RBC_reference = models.TextField(default="14 - 16g%")
PCV_reference = models.TextField(default="35 - 45 %")
MCV_reference = models.TextField(default="80 - 99 fl")
MCH_reference = models.TextField(default="28 - 32 pg")
MCHC_reference = models.TextField(default="30 - 34 %")
RDW_reference = models.TextField(default="9 - 17 fl")
Total_WBC_Count_reference = models.TextField(default="4000 - 11000 / cu.mm")
Neutrophils_reference = models.TextField(default="40 - 75 %")
Lymphocytes_reference = models.TextField(default="20 - 45 %")
Eosinophils_reference = models.TextField(default="00 - 06 %")
Monocytes_reference = models.TextField(default="00 - 10 %")
Basophils_reference = models.TextField(default="00 - 01 %")
Platelet_Count_reference = models.TextField(default="150000 - 450000 / cu.mm")
def __str__(self):
return str(self.Test_name)
Step 4: Migrate Models, after defining models, run the `makemigrations` and `migrate`
commands to create corresponding database tables based on the model definitions.
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.
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})
Day 12
Custom 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.
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:
- 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.
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})
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.
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')
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>
<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 %}
</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)
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
```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
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.
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': BASE_DIR / 'db.sqlite3',
}
}
```
```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)
```
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 migrate
```
This command executes the migration files to create the database tables.
```python
# In views.py
def product_list(request):
products = Product.objects.all()
return render(request, 'product_list.html', {'products': products})
```
```bash
python manage.py runserver
```
```bash
python manage.py createsuperuser
```
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',
'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
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.
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 -->
```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
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.
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.
- **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
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)
return redirect('home')
else:
# Handle invalid password
return render(request, 'login.html', {'error': 'Invalid password'})
except User.DoesNotExist:
# 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.
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 = '[email protected]'
EMAIL_HOST_PASSWORD = 'your_email_password'
```
```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.
```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()
```
```python
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
Ensure that you have created a template file (`email_template.html`) in your Django templates
directory.
```python
import asyncio
from django.core.mail import send_mail
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.
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**:
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')
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')
else:
return redirect('login')
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=="
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
======================-->
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/">
<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;
}
@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>
<div class="container">
<div class="py-5 text-center">
{% comment %} <img class="d-block mx-auto mb-4"
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>
<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>
<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}} >
<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">
<h4 class="mb-3">Payment</h4>
<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 %}
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=="
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"
/>
</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>
</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">
<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 %}
Day 24
“Deployment”
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.
Day 25
Day 26
Day 27
Day 28
Day 29
Day 30
Day 31
Day 32
Day 33
Day 34
Day 35
Day 36
Day 37
Day 38
Day 39
Day 40
Day 41
Day 42
Day 43
Day 44
Day 45
Tasks
# project_settings.py
PROJECT_NAME = "Ecommerce Website"
SCOPE = "To build a fully functional ecommerce platform using Django."
OBJECTIVES = ["Implement user authentication", "Create product management system",
"Integrate payment gateway"]
# 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)
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')
# 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)
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
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
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'),
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
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})
class category(models.Model):
catname = models.CharField(max_length=50)
image = models.ImageField(upload_to='imgcat')
def __str__(self):
return self.catname
else:
return render(request,'otp.html')
// 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>
<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"
>
<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">
<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 %}
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-
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-
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>
<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='
# 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
### Products
- **GET /api/products**: Get all products
- **POST /api/products**: Create a new product
## Configuration
- **Database**: PostgreSQL
- **Payment Gateway**: Stripe