Description
stringlengths 9
105
| Link
stringlengths 45
135
| Code
stringlengths 10
26.8k
| Test_Case
stringlengths 9
202
| Merge
stringlengths 63
27k
|
---|---|---|---|---|
Voting System Project Using Django Framework | https://www.geeksforgeeks.org/voting-system-project-using-django-framework/ | {% extends 'base.html' %}{% block content %}<a class ="btn btn-secondary btn-sm mb-3" href ="{% url 'polls:index' %}">Back To Polls</a><h1 class ="text-center mb-3">{{ question.question_text }}</h1>??????{% if error_message %}<p cla"alert alert-danger">????????????????????????<strong>{{ error_message }}</strong></p>??????{% endi"{% url 'polls:vote' question.id %}" method ="post">????????????????????????{% csrf_token %}????????????????????????{% for choice in question.choic"form-check">?????????????????????????????"radio" name ="choice" class ="form-check-input" id ="choice{{ forloop.counter }}"????????????????????????value ="{{ choice.id }}" />????????????????????????????"choice{{ forloop.counter }}">{{ choice.choice_text }}</label>????????????????????????</div>????????????????????????{"submit" value ="Vote" class ="btn btn-success btn-lg btn-block mt-4" /></form>{% endblock %} |
#Output : pip install pipenv | Voting System Project Using Django Framework
{% extends 'base.html' %}{% block content %}<a class ="btn btn-secondary btn-sm mb-3" href ="{% url 'polls:index' %}">Back To Polls</a><h1 class ="text-center mb-3">{{ question.question_text }}</h1>??????{% if error_message %}<p cla"alert alert-danger">????????????????????????<strong>{{ error_message }}</strong></p>??????{% endi"{% url 'polls:vote' question.id %}" method ="post">????????????????????????{% csrf_token %}????????????????????????{% for choice in question.choic"form-check">?????????????????????????????"radio" name ="choice" class ="form-check-input" id ="choice{{ forloop.counter }}"????????????????????????value ="{{ choice.id }}" />????????????????????????????"choice{{ forloop.counter }}">{{ choice.choice_text }}</label>????????????????????????</div>????????????????????????{"submit" value ="Vote" class ="btn btn-success btn-lg btn-block mt-4" /></form>{% endblock %}
#Output : pip install pipenv
[END] |
Voting System Project Using Django Framework | https://www.geeksforgeeks.org/voting-system-project-using-django-framework/ | {% extends 'base.html' %}{% block content %}<h1 class ="mb-5 text-center">{{ question.question_text }}</h1>??????<ul cla"list-group mb-5">????????????????????????{% for choice in question.choice_set.all %}???"list-group-item">????????????????????????????????????????????????{{ cho"badge badge-success float-right">{{ choice.votes }}????????????????????????????????????????????????????????????????????????vote{{ choice.votes | pluralize }}</span>??"btn btn-secondary" href ="{% url 'polls:index' %}">Back To Polls</a><a class ="btn btn-dark" href ="{% url 'polls:detail' question.id %}">Vote again?</a>{% endblock %} |
#Output : pip install pipenv | Voting System Project Using Django Framework
{% extends 'base.html' %}{% block content %}<h1 class ="mb-5 text-center">{{ question.question_text }}</h1>??????<ul cla"list-group mb-5">????????????????????????{% for choice in question.choice_set.all %}???"list-group-item">????????????????????????????????????????????????{{ cho"badge badge-success float-right">{{ choice.votes }}????????????????????????????????????????????????????????????????????????vote{{ choice.votes | pluralize }}</span>??"btn btn-secondary" href ="{% url 'polls:index' %}">Back To Polls</a><a class ="btn btn-dark" href ="{% url 'polls:detail' question.id %}">Vote again?</a>{% endblock %}
#Output : pip install pipenv
[END] |
Voting System Project Using Django Framework | https://www.geeksforgeeks.org/voting-system-project-using-django-framework/ | <nav class ="navbar navbar-dark bg-primary mb-4">????????????????????"container">??????????????????????????"navbar-brand" href ="/">Pollster</a>???????????????????? |
#Output : pip install pipenv | Voting System Project Using Django Framework
<nav class ="navbar navbar-dark bg-primary mb-4">????????????????????"container">??????????????????????????"navbar-brand" href ="/">Pollster</a>????????????????????
#Output : pip install pipenv
[END] |
Voting System Project Using Django Framework | https://www.geeksforgeeks.org/voting-system-project-using-django-framework/ | <! DOCTYPE html><html lang ="en"><head>???????????????????"stylesheet" href ="https://stackpath.bootstrapcdn.com / bootstrap / 4.4.1 / css / bootstrap.min.css"????????????????integrity ="sha384-Vkoo8x4CGsO3 + Hhxv8T / Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin ="anonymous">????????????????????????<title>Pollster {% block title %}{% endblock %}</title></head>??????<body>????????????????????????<!--NavBar-->????????????????????????{% i"container">????????????????????????????"row">????????????????????????????????????".col-md-6 m-auto">????????????????????????????????????????????????????????????????????????????????????????????????{% block content %}{% endblock %}?????????????????? |
#Output : pip install pipenv | Voting System Project Using Django Framework
<! DOCTYPE html><html lang ="en"><head>???????????????????"stylesheet" href ="https://stackpath.bootstrapcdn.com / bootstrap / 4.4.1 / css / bootstrap.min.css"????????????????integrity ="sha384-Vkoo8x4CGsO3 + Hhxv8T / Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin ="anonymous">????????????????????????<title>Pollster {% block title %}{% endblock %}</title></head>??????<body>????????????????????????<!--NavBar-->????????????????????????{% i"container">????????????????????????????"row">????????????????????????????????????".col-md-6 m-auto">????????????????????????????????????????????????????????????????????????????????????????????????{% block content %}{% endblock %}??????????????????
#Output : pip install pipenv
[END] |
Voting System Project Using Django Framework | https://www.geeksforgeeks.org/voting-system-project-using-django-framework/ | from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, "pages / index.html") |
#Output : pip install pipenv | Voting System Project Using Django Framework
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, "pages / index.html")
#Output : pip install pipenv
[END] |
Voting System Project Using Django Framework | https://www.geeksforgeeks.org/voting-system-project-using-django-framework/ | from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
] |
#Output : pip install pipenv | Voting System Project Using Django Framework
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
]
#Output : pip install pipenv
[END] |
Voting System Project Using Django Framework | https://www.geeksforgeeks.org/voting-system-project-using-django-framework/ | {% extends 'base.html' %}{% block content %}??????<div cla"card text-center">????????????????????"card-body">????????????????????????????????????????????????<h1>Welcome To Pollster</h1>??????????????????????????????????????????????????????<p>T"btn btn-dark" href ="{% url 'polls:index' %}">????????????????????????????????????????????????????????????????????????View Avail |
#Output : pip install pipenv | Voting System Project Using Django Framework
{% extends 'base.html' %}{% block content %}??????<div cla"card text-center">????????????????????"card-body">????????????????????????????????????????????????<h1>Welcome To Pollster</h1>??????????????????????????????????????????????????????<p>T"btn btn-dark" href ="{% url 'polls:index' %}">????????????????????????????????????????????????????????????????????????View Avail
#Output : pip install pipenv
[END] |
Voting System Project Using Django Framework | https://www.geeksforgeeks.org/voting-system-project-using-django-framework/ | from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("", include("pages.urls")),
path("polls/", include("polls.urls")),
path("admin/", admin.site.urls),
] |
#Output : pip install pipenv | Voting System Project Using Django Framework
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("", include("pages.urls")),
path("polls/", include("polls.urls")),
path("admin/", admin.site.urls),
]
#Output : pip install pipenv
[END] |
How to add Google reCAPTCHA to Django forms? | https://www.geeksforgeeks.org/how-to-add-google-recaptcha-to-django-forms/ | # forms.py
from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox
class ContactForm(forms.Form):
email = forms.EmailField()
feedback = forms.CharField(widget=forms.Textarea)
captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) |
#Output : django-admin startproject dj_recaptcha | How to add Google reCAPTCHA to Django forms?
# forms.py
from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox
class ContactForm(forms.Form):
email = forms.EmailField()
feedback = forms.CharField(widget=forms.Textarea)
captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox)
#Output : django-admin startproject dj_recaptcha
[END] |
How to add Google reCAPTCHA to Django forms? | https://www.geeksforgeeks.org/how-to-add-google-recaptcha-to-django-forms/ | <!DOCTYPE html><html lang="en"><head>????????????????????????<title>Contact</title></head><body>????????????????????????<h2>Contac"post">????????????????????????????????????????????????{% csrf_token %}????????????????????????????"submit">Submit</button>????????????????????????</for |
#Output : django-admin startproject dj_recaptcha | How to add Google reCAPTCHA to Django forms?
<!DOCTYPE html><html lang="en"><head>????????????????????????<title>Contact</title></head><body>????????????????????????<h2>Contac"post">????????????????????????????????????????????????{% csrf_token %}????????????????????????????"submit">Submit</button>????????????????????????</for
#Output : django-admin startproject dj_recaptcha
[END] |
How to add Google reCAPTCHA to Django forms? | https://www.geeksforgeeks.org/how-to-add-google-recaptcha-to-django-forms/ | # views.py
from django.shortcuts import render, HttpResponse
from .forms import ContactForm
def contact(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
return HttpResponse("Yay! you are human.")
else:
return HttpResponse("OOPS! Bot suspected.")
else:
form = ContactForm()
return render(request, "contact.html", {"form": form}) |
#Output : django-admin startproject dj_recaptcha | How to add Google reCAPTCHA to Django forms?
# views.py
from django.shortcuts import render, HttpResponse
from .forms import ContactForm
def contact(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
return HttpResponse("Yay! you are human.")
else:
return HttpResponse("OOPS! Bot suspected.")
else:
form = ContactForm()
return render(request, "contact.html", {"form": form})
#Output : django-admin startproject dj_recaptcha
[END] |
How to add Google reCAPTCHA to Django forms? | https://www.geeksforgeeks.org/how-to-add-google-recaptcha-to-django-forms/ | # urls.py
from django.contrib import admin
from django.urls import path
from contact import views
urlpatterns = [
path("", views.contact, name="index"),
path("admin/", admin.site.urls),
] |
#Output : django-admin startproject dj_recaptcha | How to add Google reCAPTCHA to Django forms?
# urls.py
from django.contrib import admin
from django.urls import path
from contact import views
urlpatterns = [
path("", views.contact, name="index"),
path("admin/", admin.site.urls),
]
#Output : django-admin startproject dj_recaptcha
[END] |
Youtube video downloader using Django | https://www.geeksforgeeks.org/youtube-video-downloader-using-django/ | <!DOCTYPE html><html><body>????????????<h1>Youtube video downloader</h1>?????????????"" method="post">????????????{% csrf_token %}???????????"link">Enter URL:</label>????????????<inp"text" id="link" name="link"><br><br>????????????<inp"submit" value="Submit"></form>????????????</body |
#Output : pip install pytube | Youtube video downloader using Django
<!DOCTYPE html><html><body>????????????<h1>Youtube video downloader</h1>?????????????"" method="post">????????????{% csrf_token %}???????????"link">Enter URL:</label>????????????<inp"text" id="link" name="link"><br><br>????????????<inp"submit" value="Submit"></form>????????????</body
#Output : pip install pytube
[END] |
Youtube video downloader using Django | https://www.geeksforgeeks.org/youtube-video-downloader-using-django/ | # importing all the required modules
from django.shortcuts import render, redirect
from pytube import *
# defining function
def youtube(request):
# checking whether request.method is post or not
if request.method == "POST":
# getting link from frontend
link = request.POST["link"]
video = YouTube(link)
# setting video resolution
stream = video.streams.get_lowest_resolution()
# downloads video
stream.download()
# returning HTML page
return render(request, "youtube.html")
return render(request, "youtube.html") |
#Output : pip install pytube | Youtube video downloader using Django
# importing all the required modules
from django.shortcuts import render, redirect
from pytube import *
# defining function
def youtube(request):
# checking whether request.method is post or not
if request.method == "POST":
# getting link from frontend
link = request.POST["link"]
video = YouTube(link)
# setting video resolution
stream = video.streams.get_lowest_resolution()
# downloads video
stream.download()
# returning HTML page
return render(request, "youtube.html")
return render(request, "youtube.html")
#Output : pip install pytube
[END] |
Youtube video downloader using Django | https://www.geeksforgeeks.org/youtube-video-downloader-using-django/ | from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path("admin/", admin.site.urls),
path("youtube", views.youtube, name="youtube"),
] |
#Output : pip install pytube | Youtube video downloader using Django
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path("admin/", admin.site.urls),
path("youtube", views.youtube, name="youtube"),
]
#Output : pip install pytube
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | from django.shortcuts import render, HttpResponse, redirect, HttpResponseRedirect
from django.contrib.auth import logout, authenticate, login
from .models import CustomUser, Staffs, Students, AdminHOD
from django.contrib import messages
def home(request):
return render(request, "home.html")
def contact(request):
return render(request, "contact.html")
def loginUser(request):
return render(request, "login_page.html")
def doLogin(request):
print("here")
email_id = request.GET.get("email")
password = request.GET.get("password")
# user_type = request.GET.get('user_type')
print(email_id)
print(password)
print(request.user)
if not (email_id and password):
messages.error(request, "Please provide all the details!!")
return render(request, "login_page.html")
user = CustomUser.objects.filter(email=email_id, password=password).last()
if not user:
messages.error(request, "Invalid Login Credentials!!")
return render(request, "login_page.html")
login(request, user)
print(request.user)
if user.user_type == CustomUser.STUDENT:
return redirect("student_home/")
elif user.user_type == CustomUser.STAFF:
return redirect("staff_home/")
elif user.user_type == CustomUser.HOD:
return redirect("admin_home/")
return render(request, "home.html")
def registration(request):
return render(request, "registration.html")
def doRegistration(request):
first_name = request.GET.get("first_name")
last_name = request.GET.get("last_name")
email_id = request.GET.get("email")
password = request.GET.get("password")
confirm_password = request.GET.get("confirmPassword")
print(email_id)
print(password)
print(confirm_password)
print(first_name)
print(last_name)
if not (email_id and password and confirm_password):
messages.error(request, "Please provide all the details!!")
return render(request, "registration.html")
if password != confirm_password:
messages.error(request, "Both passwords should match!!")
return render(request, "registration.html")
is_user_exists = CustomUser.objects.filter(email=email_id).exists()
if is_user_exists:
messages.error(
request, "User with this email id already exists. Please proceed to login!!"
)
return render(request, "registration.html")
user_type = get_user_type_from_email(email_id)
if user_type is None:
messages.error(
request,
"Please use valid format for the email id: '<username>.<staff|student|hod>@<college_domain>'",
)
return render(request, "registration.html")
username = email_id.split("@")[0].split(".")[0]
if CustomUser.objects.filter(username=username).exists():
messages.error(
request,
"User with this username already exists. Please use different username",
)
return render(request, "registration.html")
user = CustomUser()
user.username = username
user.email = email_id
user.password = password
user.user_type = user_type
user.first_name = first_name
user.last_name = last_name
user.save()
if user_type == CustomUser.STAFF:
Staffs.objects.create(admin=user)
elif user_type == CustomUser.STUDENT:
Students.objects.create(admin=user)
elif user_type == CustomUser.HOD:
AdminHOD.objects.create(admin=user)
return render(request, "login_page.html")
def logout_user(request):
logout(request)
return HttpResponseRedirect("/")
def get_user_type_from_email(email_id):
"""
Returns CustomUser.user_type corresponding to the given email address
email_id should be in following format:
'<username>.<staff|student|hod>@<college_domain>'
eg.: 'abhishek.staff@jecrc.com'
"""
try:
email_id = email_id.split("@")[0]
email_user_type = email_id.split(".")[1]
return CustomUser.EMAIL_TO_USER_TYPE_MAP[email_user_type]
except:
return None |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
from django.shortcuts import render, HttpResponse, redirect, HttpResponseRedirect
from django.contrib.auth import logout, authenticate, login
from .models import CustomUser, Staffs, Students, AdminHOD
from django.contrib import messages
def home(request):
return render(request, "home.html")
def contact(request):
return render(request, "contact.html")
def loginUser(request):
return render(request, "login_page.html")
def doLogin(request):
print("here")
email_id = request.GET.get("email")
password = request.GET.get("password")
# user_type = request.GET.get('user_type')
print(email_id)
print(password)
print(request.user)
if not (email_id and password):
messages.error(request, "Please provide all the details!!")
return render(request, "login_page.html")
user = CustomUser.objects.filter(email=email_id, password=password).last()
if not user:
messages.error(request, "Invalid Login Credentials!!")
return render(request, "login_page.html")
login(request, user)
print(request.user)
if user.user_type == CustomUser.STUDENT:
return redirect("student_home/")
elif user.user_type == CustomUser.STAFF:
return redirect("staff_home/")
elif user.user_type == CustomUser.HOD:
return redirect("admin_home/")
return render(request, "home.html")
def registration(request):
return render(request, "registration.html")
def doRegistration(request):
first_name = request.GET.get("first_name")
last_name = request.GET.get("last_name")
email_id = request.GET.get("email")
password = request.GET.get("password")
confirm_password = request.GET.get("confirmPassword")
print(email_id)
print(password)
print(confirm_password)
print(first_name)
print(last_name)
if not (email_id and password and confirm_password):
messages.error(request, "Please provide all the details!!")
return render(request, "registration.html")
if password != confirm_password:
messages.error(request, "Both passwords should match!!")
return render(request, "registration.html")
is_user_exists = CustomUser.objects.filter(email=email_id).exists()
if is_user_exists:
messages.error(
request, "User with this email id already exists. Please proceed to login!!"
)
return render(request, "registration.html")
user_type = get_user_type_from_email(email_id)
if user_type is None:
messages.error(
request,
"Please use valid format for the email id: '<username>.<staff|student|hod>@<college_domain>'",
)
return render(request, "registration.html")
username = email_id.split("@")[0].split(".")[0]
if CustomUser.objects.filter(username=username).exists():
messages.error(
request,
"User with this username already exists. Please use different username",
)
return render(request, "registration.html")
user = CustomUser()
user.username = username
user.email = email_id
user.password = password
user.user_type = user_type
user.first_name = first_name
user.last_name = last_name
user.save()
if user_type == CustomUser.STAFF:
Staffs.objects.create(admin=user)
elif user_type == CustomUser.STUDENT:
Students.objects.create(admin=user)
elif user_type == CustomUser.HOD:
AdminHOD.objects.create(admin=user)
return render(request, "login_page.html")
def logout_user(request):
logout(request)
return HttpResponseRedirect("/")
def get_user_type_from_email(email_id):
"""
Returns CustomUser.user_type corresponding to the given email address
email_id should be in following format:
'<username>.<staff|student|hod>@<college_domain>'
eg.: 'abhishek.staff@jecrc.com'
"""
try:
email_id = email_id.split("@")[0]
email_user_type = email_id.split(".")[1]
return CustomUser.EMAIL_TO_USER_TYPE_MAP[email_user_type]
except:
return None
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | from django.contrib import admin
from django.urls import path, include
from . import views
from . import HodViews, StaffViews, StudentViews
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.home, name="home"),
path("contact", views.contact, name="contact"),
path("login", views.loginUser, name="login"),
path("logout_user", views.logout_user, name="logout_user"),
path("registration", views.registration, name="registration"),
path("doLogin", views.doLogin, name="doLogin"),
path("doRegistration", views.doRegistration, name="doRegistration"),
# URLS for Student
path("student_home/", StudentViews.student_home, name="student_home"),
path(
"student_view_attendance/",
StudentViews.student_view_attendance,
name="student_view_attendance",
),
path(
"student_view_attendance_post/",
StudentViews.student_view_attendance_post,
name="student_view_attendance_post",
),
path(
"student_apply_leave/",
StudentViews.student_apply_leave,
name="student_apply_leave",
),
path(
"student_apply_leave_save/",
StudentViews.student_apply_leave_save,
name="student_apply_leave_save",
),
path("student_feedback/", StudentViews.student_feedback, name="student_feedback"),
path(
"student_feedback_save/",
StudentViews.student_feedback_save,
name="student_feedback_save",
),
path("student_profile/", StudentViews.student_profile, name="student_profile"),
path(
"student_profile_update/",
StudentViews.student_profile_update,
name="student_profile_update",
),
path(
"student_view_result/",
StudentViews.student_view_result,
name="student_view_result",
),
# URLS for Staff
path("staff_home/", StaffViews.staff_home, name="staff_home"),
path(
"staff_take_attendance/",
StaffViews.staff_take_attendance,
name="staff_take_attendance",
),
path("get_students/", StaffViews.get_students, name="get_students"),
path(
"save_attendance_data/",
StaffViews.save_attendance_data,
name="save_attendance_data",
),
path(
"staff_update_attendance/",
StaffViews.staff_update_attendance,
name="staff_update_attendance",
),
path(
"get_attendance_dates/",
StaffViews.get_attendance_dates,
name="get_attendance_dates",
),
path(
"get_attendance_student/",
StaffViews.get_attendance_student,
name="get_attendance_student",
),
path(
"update_attendance_data/",
StaffViews.update_attendance_data,
name="update_attendance_data",
),
path("staff_apply_leave/", StaffViews.staff_apply_leave, name="staff_apply_leave"),
path(
"staff_apply_leave_save/",
StaffViews.staff_apply_leave_save,
name="staff_apply_leave_save",
),
path("staff_feedback/", StaffViews.staff_feedback, name="staff_feedback"),
path(
"staff_feedback_save/",
StaffViews.staff_feedback_save,
name="staff_feedback_save",
),
path("staff_profile/", StaffViews.staff_profile, name="staff_profile"),
path(
"staff_profile_update/",
StaffViews.staff_profile_update,
name="staff_profile_update",
),
path("staff_add_result/", StaffViews.staff_add_result, name="staff_add_result"),
path(
"staff_add_result_save/",
StaffViews.staff_add_result_save,
name="staff_add_result_save",
),
# URL for Admin
path("admin_home/", HodViews.admin_home, name="admin_home"),
path("add_staff/", HodViews.add_staff, name="add_staff"),
path("add_staff_save/", HodViews.add_staff_save, name="add_staff_save"),
path("manage_staff/", HodViews.manage_staff, name="manage_staff"),
path("edit_staff/<staff_id>/", HodViews.edit_staff, name="edit_staff"),
path("edit_staff_save/", HodViews.edit_staff_save, name="edit_staff_save"),
path("delete_staff/<staff_id>/", HodViews.delete_staff, name="delete_staff"),
path("add_course/", HodViews.add_course, name="add_course"),
path("add_course_save/", HodViews.add_course_save, name="add_course_save"),
path("manage_course/", HodViews.manage_course, name="manage_course"),
path("edit_course/<course_id>/", HodViews.edit_course, name="edit_course"),
path("edit_course_save/", HodViews.edit_course_save, name="edit_course_save"),
path("delete_course/<course_id>/", HodViews.delete_course, name="delete_course"),
path("manage_session/", HodViews.manage_session, name="manage_session"),
path("add_session/", HodViews.add_session, name="add_session"),
path("add_session_save/", HodViews.add_session_save, name="add_session_save"),
path("edit_session/<session_id>", HodViews.edit_session, name="edit_session"),
path("edit_session_save/", HodViews.edit_session_save, name="edit_session_save"),
path(
"delete_session/<session_id>/", HodViews.delete_session, name="delete_session"
),
path("add_student/", HodViews.add_student, name="add_student"),
path("add_student_save/", HodViews.add_student_save, name="add_student_save"),
path("edit_student/<student_id>", HodViews.edit_student, name="edit_student"),
path("edit_student_save/", HodViews.edit_student_save, name="edit_student_save"),
path("manage_student/", HodViews.manage_student, name="manage_student"),
path(
"delete_student/<student_id>/", HodViews.delete_student, name="delete_student"
),
path("add_subject/", HodViews.add_subject, name="add_subject"),
path("add_subject_save/", HodViews.add_subject_save, name="add_subject_save"),
path("manage_subject/", HodViews.manage_subject, name="manage_subject"),
path("edit_subject/<subject_id>/", HodViews.edit_subject, name="edit_subject"),
path("edit_subject_save/", HodViews.edit_subject_save, name="edit_subject_save"),
path(
"delete_subject/<subject_id>/", HodViews.delete_subject, name="delete_subject"
),
path("check_email_exist/", HodViews.check_email_exist, name="check_email_exist"),
path(
"check_username_exist/",
HodViews.check_username_exist,
name="check_username_exist",
),
path(
"student_feedback_message/",
HodViews.student_feedback_message,
name="student_feedback_message",
),
path(
"student_feedback_message_reply/",
HodViews.student_feedback_message_reply,
name="student_feedback_message_reply",
),
path(
"staff_feedback_message/",
HodViews.staff_feedback_message,
name="staff_feedback_message",
),
path(
"staff_feedback_message_reply/",
HodViews.staff_feedback_message_reply,
name="staff_feedback_message_reply",
),
path("student_leave_view/", HodViews.student_leave_view, name="student_leave_view"),
path(
"student_leave_approve/<leave_id>/",
HodViews.student_leave_approve,
name="student_leave_approve",
),
path(
"student_leave_reject/<leave_id>/",
HodViews.student_leave_reject,
name="student_leave_reject",
),
path("staff_leave_view/", HodViews.staff_leave_view, name="staff_leave_view"),
path(
"staff_leave_approve/<leave_id>/",
HodViews.staff_leave_approve,
name="staff_leave_approve",
),
path(
"staff_leave_reject/<leave_id>/",
HodViews.staff_leave_reject,
name="staff_leave_reject",
),
path(
"admin_view_attendance/",
HodViews.admin_view_attendance,
name="admin_view_attendance",
),
path(
"admin_get_attendance_dates/",
HodViews.admin_get_attendance_dates,
name="admin_get_attendance_dates",
),
path(
"admin_get_attendance_student/",
HodViews.admin_get_attendance_student,
name="admin_get_attendance_student",
),
path("admin_profile/", HodViews.admin_profile, name="admin_profile"),
path(
"admin_profile_update/",
HodViews.admin_profile_update,
name="admin_profile_update",
),
] |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
from django.contrib import admin
from django.urls import path, include
from . import views
from . import HodViews, StaffViews, StudentViews
urlpatterns = [
path("admin/", admin.site.urls),
path("", views.home, name="home"),
path("contact", views.contact, name="contact"),
path("login", views.loginUser, name="login"),
path("logout_user", views.logout_user, name="logout_user"),
path("registration", views.registration, name="registration"),
path("doLogin", views.doLogin, name="doLogin"),
path("doRegistration", views.doRegistration, name="doRegistration"),
# URLS for Student
path("student_home/", StudentViews.student_home, name="student_home"),
path(
"student_view_attendance/",
StudentViews.student_view_attendance,
name="student_view_attendance",
),
path(
"student_view_attendance_post/",
StudentViews.student_view_attendance_post,
name="student_view_attendance_post",
),
path(
"student_apply_leave/",
StudentViews.student_apply_leave,
name="student_apply_leave",
),
path(
"student_apply_leave_save/",
StudentViews.student_apply_leave_save,
name="student_apply_leave_save",
),
path("student_feedback/", StudentViews.student_feedback, name="student_feedback"),
path(
"student_feedback_save/",
StudentViews.student_feedback_save,
name="student_feedback_save",
),
path("student_profile/", StudentViews.student_profile, name="student_profile"),
path(
"student_profile_update/",
StudentViews.student_profile_update,
name="student_profile_update",
),
path(
"student_view_result/",
StudentViews.student_view_result,
name="student_view_result",
),
# URLS for Staff
path("staff_home/", StaffViews.staff_home, name="staff_home"),
path(
"staff_take_attendance/",
StaffViews.staff_take_attendance,
name="staff_take_attendance",
),
path("get_students/", StaffViews.get_students, name="get_students"),
path(
"save_attendance_data/",
StaffViews.save_attendance_data,
name="save_attendance_data",
),
path(
"staff_update_attendance/",
StaffViews.staff_update_attendance,
name="staff_update_attendance",
),
path(
"get_attendance_dates/",
StaffViews.get_attendance_dates,
name="get_attendance_dates",
),
path(
"get_attendance_student/",
StaffViews.get_attendance_student,
name="get_attendance_student",
),
path(
"update_attendance_data/",
StaffViews.update_attendance_data,
name="update_attendance_data",
),
path("staff_apply_leave/", StaffViews.staff_apply_leave, name="staff_apply_leave"),
path(
"staff_apply_leave_save/",
StaffViews.staff_apply_leave_save,
name="staff_apply_leave_save",
),
path("staff_feedback/", StaffViews.staff_feedback, name="staff_feedback"),
path(
"staff_feedback_save/",
StaffViews.staff_feedback_save,
name="staff_feedback_save",
),
path("staff_profile/", StaffViews.staff_profile, name="staff_profile"),
path(
"staff_profile_update/",
StaffViews.staff_profile_update,
name="staff_profile_update",
),
path("staff_add_result/", StaffViews.staff_add_result, name="staff_add_result"),
path(
"staff_add_result_save/",
StaffViews.staff_add_result_save,
name="staff_add_result_save",
),
# URL for Admin
path("admin_home/", HodViews.admin_home, name="admin_home"),
path("add_staff/", HodViews.add_staff, name="add_staff"),
path("add_staff_save/", HodViews.add_staff_save, name="add_staff_save"),
path("manage_staff/", HodViews.manage_staff, name="manage_staff"),
path("edit_staff/<staff_id>/", HodViews.edit_staff, name="edit_staff"),
path("edit_staff_save/", HodViews.edit_staff_save, name="edit_staff_save"),
path("delete_staff/<staff_id>/", HodViews.delete_staff, name="delete_staff"),
path("add_course/", HodViews.add_course, name="add_course"),
path("add_course_save/", HodViews.add_course_save, name="add_course_save"),
path("manage_course/", HodViews.manage_course, name="manage_course"),
path("edit_course/<course_id>/", HodViews.edit_course, name="edit_course"),
path("edit_course_save/", HodViews.edit_course_save, name="edit_course_save"),
path("delete_course/<course_id>/", HodViews.delete_course, name="delete_course"),
path("manage_session/", HodViews.manage_session, name="manage_session"),
path("add_session/", HodViews.add_session, name="add_session"),
path("add_session_save/", HodViews.add_session_save, name="add_session_save"),
path("edit_session/<session_id>", HodViews.edit_session, name="edit_session"),
path("edit_session_save/", HodViews.edit_session_save, name="edit_session_save"),
path(
"delete_session/<session_id>/", HodViews.delete_session, name="delete_session"
),
path("add_student/", HodViews.add_student, name="add_student"),
path("add_student_save/", HodViews.add_student_save, name="add_student_save"),
path("edit_student/<student_id>", HodViews.edit_student, name="edit_student"),
path("edit_student_save/", HodViews.edit_student_save, name="edit_student_save"),
path("manage_student/", HodViews.manage_student, name="manage_student"),
path(
"delete_student/<student_id>/", HodViews.delete_student, name="delete_student"
),
path("add_subject/", HodViews.add_subject, name="add_subject"),
path("add_subject_save/", HodViews.add_subject_save, name="add_subject_save"),
path("manage_subject/", HodViews.manage_subject, name="manage_subject"),
path("edit_subject/<subject_id>/", HodViews.edit_subject, name="edit_subject"),
path("edit_subject_save/", HodViews.edit_subject_save, name="edit_subject_save"),
path(
"delete_subject/<subject_id>/", HodViews.delete_subject, name="delete_subject"
),
path("check_email_exist/", HodViews.check_email_exist, name="check_email_exist"),
path(
"check_username_exist/",
HodViews.check_username_exist,
name="check_username_exist",
),
path(
"student_feedback_message/",
HodViews.student_feedback_message,
name="student_feedback_message",
),
path(
"student_feedback_message_reply/",
HodViews.student_feedback_message_reply,
name="student_feedback_message_reply",
),
path(
"staff_feedback_message/",
HodViews.staff_feedback_message,
name="staff_feedback_message",
),
path(
"staff_feedback_message_reply/",
HodViews.staff_feedback_message_reply,
name="staff_feedback_message_reply",
),
path("student_leave_view/", HodViews.student_leave_view, name="student_leave_view"),
path(
"student_leave_approve/<leave_id>/",
HodViews.student_leave_approve,
name="student_leave_approve",
),
path(
"student_leave_reject/<leave_id>/",
HodViews.student_leave_reject,
name="student_leave_reject",
),
path("staff_leave_view/", HodViews.staff_leave_view, name="staff_leave_view"),
path(
"staff_leave_approve/<leave_id>/",
HodViews.staff_leave_approve,
name="staff_leave_approve",
),
path(
"staff_leave_reject/<leave_id>/",
HodViews.staff_leave_reject,
name="staff_leave_reject",
),
path(
"admin_view_attendance/",
HodViews.admin_view_attendance,
name="admin_view_attendance",
),
path(
"admin_get_attendance_dates/",
HodViews.admin_get_attendance_dates,
name="admin_get_attendance_dates",
),
path(
"admin_get_attendance_student/",
HodViews.admin_get_attendance_student,
name="admin_get_attendance_student",
),
path("admin_profile/", HodViews.admin_profile, name="admin_profile"),
path(
"admin_profile_update/",
HodViews.admin_profile_update,
name="admin_profile_update",
),
]
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.core.files.storage import FileSystemStorage
from django.urls import reverse
import datetime
from .models import (
CustomUser,
Staffs,
Courses,
Subjects,
Students,
Attendance,
AttendanceReport,
LeaveReportStudent,
FeedBackStudent,
StudentResult,
)
def student_home(request):
student_obj = Students.objects.get(admin=request.user.id)
total_attendance = AttendanceReport.objects.filter(student_id=student_obj).count()
attendance_present = AttendanceReport.objects.filter(
student_id=student_obj, status=True
).count()
attendance_absent = AttendanceReport.objects.filter(
student_id=student_obj, status=False
).count()
course_obj = Courses.objects.get(id=student_obj.course_id.id)
total_subjects = Subjects.objects.filter(course_id=course_obj).count()
subject_name = []
data_present = []
data_absent = []
subject_data = Subjects.objects.filter(course_id=student_obj.course_id)
for subject in subject_data:
attendance = Attendance.objects.filter(subject_id=subject.id)
attendance_present_count = AttendanceReport.objects.filter(
attendance_id__in=attendance, status=True, student_id=student_obj.id
).count()
attendance_absent_count = AttendanceReport.objects.filter(
attendance_id__in=attendance, status=False, student_id=student_obj.id
).count()
subject_name.append(subject.subject_name)
data_present.append(attendance_present_count)
data_absent.append(attendance_absent_count)
context = {
"total_attendance": total_attendance,
"attendance_present": attendance_present,
"attendance_absent": attendance_absent,
"total_subjects": total_subjects,
"subject_name": subject_name,
"data_present": data_present,
"data_absent": data_absent,
}
return render(request, "student_template/student_home_template.html")
def student_view_attendance(request):
# Getting Logged in Student Data
student = Students.objects.get(admin=request.user.id)
# Getting Course Enrolled of LoggedIn Student
course = student.course_id
# Getting the Subjects of Course Enrolled
subjects = Subjects.objects.filter(course_id=course)
context = {"subjects": subjects}
return render(request, "student_template/student_view_attendance.html", context)
def student_view_attendance_post(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("student_view_attendance")
else:
# Getting all the Input Data
subject_id = request.POST.get("subject")
start_date = request.POST.get("start_date")
end_date = request.POST.get("end_date")
# Parsing the date data into Python object
start_date_parse = datetime.datetime.strptime(start_date, "%Y-%m-%d").date()
end_date_parse = datetime.datetime.strptime(end_date, "%Y-%m-%d").date()
# Getting all the Subject Data based on Selected Subject
subject_obj = Subjects.objects.get(id=subject_id)
# Getting Logged In User Data
user_obj = CustomUser.objects.get(id=request.user.id)
# Getting Student Data Based on Logged in Data
stud_obj = Students.objects.get(admin=user_obj)
# Now Accessing Attendance Data based on the Range of Date
# Selected and Subject Selected
attendance = Attendance.objects.filter(
attendance_date__range=(start_date_parse, end_date_parse),
subject_id=subject_obj,
)
# Getting Attendance Report based on the attendance
# details obtained above
attendance_reports = AttendanceReport.objects.filter(
attendance_id__in=attendance, student_id=stud_obj
)
context = {"subject_obj": subject_obj, "attendance_reports": attendance_reports}
return render(request, "student_template/student_attendance_data.html", context)
def student_apply_leave(request):
student_obj = Students.objects.get(admin=request.user.id)
leave_data = LeaveReportStudent.objects.filter(student_id=student_obj)
context = {"leave_data": leave_data}
return render(request, "student_template/student_apply_leave.html", context)
def student_apply_leave_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("student_apply_leave")
else:
leave_date = request.POST.get("leave_date")
leave_message = request.POST.get("leave_message")
student_obj = Students.objects.get(admin=request.user.id)
try:
leave_report = LeaveReportStudent(
student_id=student_obj,
leave_date=leave_date,
leave_message=leave_message,
leave_status=0,
)
leave_report.save()
messages.success(request, "Applied for Leave.")
return redirect("student_apply_leave")
except:
messages.error(request, "Failed to Apply Leave")
return redirect("student_apply_leave")
def student_feedback(request):
student_obj = Students.objects.get(admin=request.user.id)
feedback_data = FeedBackStudent.objects.filter(student_id=student_obj)
context = {"feedback_data": feedback_data}
return render(request, "student_template/student_feedback.html", context)
def student_feedback_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method.")
return redirect("student_feedback")
else:
feedback = request.POST.get("feedback_message")
student_obj = Students.objects.get(admin=request.user.id)
try:
add_feedback = FeedBackStudent(
student_id=student_obj, feedback=feedback, feedback_reply=""
)
add_feedback.save()
messages.success(request, "Feedback Sent.")
return redirect("student_feedback")
except:
messages.error(request, "Failed to Send Feedback.")
return redirect("student_feedback")
def student_profile(request):
user = CustomUser.objects.get(id=request.user.id)
student = Students.objects.get(admin=user)
context = {"user": user, "student": student}
return render(request, "student_template/student_profile.html", context)
def student_profile_update(request):
if request.method != "POST":
messages.error(request, "Invalid Method!")
return redirect("student_profile")
else:
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
password = request.POST.get("password")
address = request.POST.get("address")
try:
customuser = CustomUser.objects.get(id=request.user.id)
customuser.first_name = first_name
customuser.last_name = last_name
if password != None and password != "":
customuser.set_password(password)
customuser.save()
student = Students.objects.get(admin=customuser.id)
student.address = address
student.save()
messages.success(request, "Profile Updated Successfully")
return redirect("student_profile")
except:
messages.error(request, "Failed to Update Profile")
return redirect("student_profile")
def student_view_result(request):
student = Students.objects.get(admin=request.user.id)
student_result = StudentResult.objects.filter(student_id=student.id)
context = {
"student_result": student_result,
}
return render(request, "student_template/student_view_result.html", context) |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from django.core.files.storage import FileSystemStorage
from django.urls import reverse
import datetime
from .models import (
CustomUser,
Staffs,
Courses,
Subjects,
Students,
Attendance,
AttendanceReport,
LeaveReportStudent,
FeedBackStudent,
StudentResult,
)
def student_home(request):
student_obj = Students.objects.get(admin=request.user.id)
total_attendance = AttendanceReport.objects.filter(student_id=student_obj).count()
attendance_present = AttendanceReport.objects.filter(
student_id=student_obj, status=True
).count()
attendance_absent = AttendanceReport.objects.filter(
student_id=student_obj, status=False
).count()
course_obj = Courses.objects.get(id=student_obj.course_id.id)
total_subjects = Subjects.objects.filter(course_id=course_obj).count()
subject_name = []
data_present = []
data_absent = []
subject_data = Subjects.objects.filter(course_id=student_obj.course_id)
for subject in subject_data:
attendance = Attendance.objects.filter(subject_id=subject.id)
attendance_present_count = AttendanceReport.objects.filter(
attendance_id__in=attendance, status=True, student_id=student_obj.id
).count()
attendance_absent_count = AttendanceReport.objects.filter(
attendance_id__in=attendance, status=False, student_id=student_obj.id
).count()
subject_name.append(subject.subject_name)
data_present.append(attendance_present_count)
data_absent.append(attendance_absent_count)
context = {
"total_attendance": total_attendance,
"attendance_present": attendance_present,
"attendance_absent": attendance_absent,
"total_subjects": total_subjects,
"subject_name": subject_name,
"data_present": data_present,
"data_absent": data_absent,
}
return render(request, "student_template/student_home_template.html")
def student_view_attendance(request):
# Getting Logged in Student Data
student = Students.objects.get(admin=request.user.id)
# Getting Course Enrolled of LoggedIn Student
course = student.course_id
# Getting the Subjects of Course Enrolled
subjects = Subjects.objects.filter(course_id=course)
context = {"subjects": subjects}
return render(request, "student_template/student_view_attendance.html", context)
def student_view_attendance_post(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("student_view_attendance")
else:
# Getting all the Input Data
subject_id = request.POST.get("subject")
start_date = request.POST.get("start_date")
end_date = request.POST.get("end_date")
# Parsing the date data into Python object
start_date_parse = datetime.datetime.strptime(start_date, "%Y-%m-%d").date()
end_date_parse = datetime.datetime.strptime(end_date, "%Y-%m-%d").date()
# Getting all the Subject Data based on Selected Subject
subject_obj = Subjects.objects.get(id=subject_id)
# Getting Logged In User Data
user_obj = CustomUser.objects.get(id=request.user.id)
# Getting Student Data Based on Logged in Data
stud_obj = Students.objects.get(admin=user_obj)
# Now Accessing Attendance Data based on the Range of Date
# Selected and Subject Selected
attendance = Attendance.objects.filter(
attendance_date__range=(start_date_parse, end_date_parse),
subject_id=subject_obj,
)
# Getting Attendance Report based on the attendance
# details obtained above
attendance_reports = AttendanceReport.objects.filter(
attendance_id__in=attendance, student_id=stud_obj
)
context = {"subject_obj": subject_obj, "attendance_reports": attendance_reports}
return render(request, "student_template/student_attendance_data.html", context)
def student_apply_leave(request):
student_obj = Students.objects.get(admin=request.user.id)
leave_data = LeaveReportStudent.objects.filter(student_id=student_obj)
context = {"leave_data": leave_data}
return render(request, "student_template/student_apply_leave.html", context)
def student_apply_leave_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("student_apply_leave")
else:
leave_date = request.POST.get("leave_date")
leave_message = request.POST.get("leave_message")
student_obj = Students.objects.get(admin=request.user.id)
try:
leave_report = LeaveReportStudent(
student_id=student_obj,
leave_date=leave_date,
leave_message=leave_message,
leave_status=0,
)
leave_report.save()
messages.success(request, "Applied for Leave.")
return redirect("student_apply_leave")
except:
messages.error(request, "Failed to Apply Leave")
return redirect("student_apply_leave")
def student_feedback(request):
student_obj = Students.objects.get(admin=request.user.id)
feedback_data = FeedBackStudent.objects.filter(student_id=student_obj)
context = {"feedback_data": feedback_data}
return render(request, "student_template/student_feedback.html", context)
def student_feedback_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method.")
return redirect("student_feedback")
else:
feedback = request.POST.get("feedback_message")
student_obj = Students.objects.get(admin=request.user.id)
try:
add_feedback = FeedBackStudent(
student_id=student_obj, feedback=feedback, feedback_reply=""
)
add_feedback.save()
messages.success(request, "Feedback Sent.")
return redirect("student_feedback")
except:
messages.error(request, "Failed to Send Feedback.")
return redirect("student_feedback")
def student_profile(request):
user = CustomUser.objects.get(id=request.user.id)
student = Students.objects.get(admin=user)
context = {"user": user, "student": student}
return render(request, "student_template/student_profile.html", context)
def student_profile_update(request):
if request.method != "POST":
messages.error(request, "Invalid Method!")
return redirect("student_profile")
else:
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
password = request.POST.get("password")
address = request.POST.get("address")
try:
customuser = CustomUser.objects.get(id=request.user.id)
customuser.first_name = first_name
customuser.last_name = last_name
if password != None and password != "":
customuser.set_password(password)
customuser.save()
student = Students.objects.get(admin=customuser.id)
student.address = address
student.save()
messages.success(request, "Profile Updated Successfully")
return redirect("student_profile")
except:
messages.error(request, "Failed to Update Profile")
return redirect("student_profile")
def student_view_result(request):
student = Students.objects.get(admin=request.user.id)
student_result = StudentResult.objects.filter(student_id=student.id)
context = {
"student_result": student_result,
}
return render(request, "student_template/student_view_result.html", context)
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib import messages
from django.core.files.storage import FileSystemStorage
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
import json
from .models import (
CustomUser,
Staffs,
Courses,
Subjects,
Students,
SessionYearModel,
Attendance,
AttendanceReport,
LeaveReportStaff,
FeedBackStaffs,
StudentResult,
)
def staff_home(request):
# Fetching All Students under Staff
print(request.user.id)
subjects = Subjects.objects.filter(staff_id=request.user.id)
print(subjects)
course_id_list = []
for subject in subjects:
course = Courses.objects.get(id=subject.course_id.id)
course_id_list.append(course.id)
final_course = []
# Removing Duplicate Course Id
for course_id in course_id_list:
if course_id not in final_course:
final_course.append(course_id)
print(final_course)
students_count = Students.objects.filter(course_id__in=final_course).count()
subject_count = subjects.count()
print(subject_count)
print(students_count)
# Fetch All Attendance Count
attendance_count = Attendance.objects.filter(subject_id__in=subjects).count()
# Fetch All Approve Leave
# print(request.user)
print(request.user.user_type)
staff = Staffs.objects.get(admin=request.user.id)
leave_count = LeaveReportStaff.objects.filter(
staff_id=staff.id, leave_status=1
).count()
# Fetch Attendance Data by Subjects
subject_list = []
attendance_list = []
for subject in subjects:
attendance_count1 = Attendance.objects.filter(subject_id=subject.id).count()
subject_list.append(subject.subject_name)
attendance_list.append(attendance_count1)
students_attendance = Students.objects.filter(course_id__in=final_course)
student_list = []
student_list_attendance_present = []
student_list_attendance_absent = []
for student in students_attendance:
attendance_present_count = AttendanceReport.objects.filter(
status=True, student_id=student.id
).count()
attendance_absent_count = AttendanceReport.objects.filter(
status=False, student_id=student.id
).count()
student_list.append(student.admin.first_name + " " + student.admin.last_name)
student_list_attendance_present.append(attendance_present_count)
student_list_attendance_absent.append(attendance_absent_count)
context = {
"students_count": students_count,
"attendance_count": attendance_count,
"leave_count": leave_count,
"subject_count": subject_count,
"subject_list": subject_list,
"attendance_list": attendance_list,
"student_list": student_list,
"attendance_present_list": student_list_attendance_present,
"attendance_absent_list": student_list_attendance_absent,
}
return render(request, "staff_template/staff_home_template.html", context)
def staff_take_attendance(request):
subjects = Subjects.objects.filter(staff_id=request.user.id)
session_years = SessionYearModel.objects.all()
context = {"subjects": subjects, "session_years": session_years}
return render(request, "staff_template/take_attendance_template.html", context)
def staff_apply_leave(request):
print(request.user.id)
staff_obj = Staffs.objects.get(admin=request.user.id)
leave_data = LeaveReportStaff.objects.filter(staff_id=staff_obj)
context = {"leave_data": leave_data}
return render(request, "staff_template/staff_apply_leave_template.html", context)
def staff_apply_leave_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("staff_apply_leave")
else:
leave_date = request.POST.get("leave_date")
leave_message = request.POST.get("leave_message")
staff_obj = Staffs.objects.get(admin=request.user.id)
try:
leave_report = LeaveReportStaff(
staff_id=staff_obj,
leave_date=leave_date,
leave_message=leave_message,
leave_status=0,
)
leave_report.save()
messages.success(request, "Applied for Leave.")
return redirect("staff_apply_leave")
except:
messages.error(request, "Failed to Apply Leave")
return redirect("staff_apply_leave")
def staff_feedback(request):
return render(request, "staff_template/staff_feedback_template.html")
def staff_feedback_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method.")
return redirect("staff_feedback")
else:
feedback = request.POST.get("feedback_message")
staff_obj = Staffs.objects.get(admin=request.user.id)
try:
add_feedback = FeedBackStaffs(
staff_id=staff_obj, feedback=feedback, feedback_reply=""
)
add_feedback.save()
messages.success(request, "Feedback Sent.")
return redirect("staff_feedback")
except:
messages.error(request, "Failed to Send Feedback.")
return redirect("staff_feedback")
@csrf_exempt
def get_students(request):
subject_id = request.POST.get("subject")
session_year = request.POST.get("session_year")
# Students enroll to Course, Course has Subjects
# Getting all data from subject model based on subject_id
subject_model = Subjects.objects.get(id=subject_id)
session_model = SessionYearModel.objects.get(id=session_year)
students = Students.objects.filter(
course_id=subject_model.course_id, session_year_id=session_model
)
# Only Passing Student Id and Student Name Only
list_data = []
for student in students:
data_small = {
"id": student.admin.id,
"name": student.admin.first_name + " " + student.admin.last_name,
}
list_data.append(data_small)
return JsonResponse(
json.dumps(list_data), content_type="application/json", safe=False
)
@csrf_exempt
def save_attendance_data(request):
# Get Values from Staf Take Attendance form via AJAX (JavaScript)
# Use getlist to access HTML Array/List Input Data
student_ids = request.POST.get("student_ids")
subject_id = request.POST.get("subject_id")
attendance_date = request.POST.get("attendance_date")
session_year_id = request.POST.get("session_year_id")
subject_model = Subjects.objects.get(id=subject_id)
session_year_model = SessionYearModel.objects.get(id=session_year_id)
json_student = json.loads(student_ids)
try:
# First Attendance Data is Saved on Attendance Model
attendance = Attendance(
subject_id=subject_model,
attendance_date=attendance_date,
session_year_id=session_year_model,
)
attendance.save()
for stud in json_student:
# Attendance of Individual Student saved on AttendanceReport Model
student = Students.objects.get(admin=stud["id"])
attendance_report = AttendanceReport(
student_id=student, attendance_id=attendance, status=stud["status"]
)
attendance_report.save()
return HttpResponse("OK")
except:
return HttpResponse("Error")
def staff_update_attendance(request):
subjects = Subjects.objects.filter(staff_id=request.user.id)
session_years = SessionYearModel.objects.all()
context = {"subjects": subjects, "session_years": session_years}
return render(request, "staff_template/update_attendance_template.html", context)
@csrf_exempt
def get_attendance_dates(request):
# Getting Values from Ajax POST 'Fetch Student'
subject_id = request.POST.get("subject")
session_year = request.POST.get("session_year_id")
# Students enroll to Course, Course has Subjects
# Getting all data from subject model based on subject_id
subject_model = Subjects.objects.get(id=subject_id)
session_model = SessionYearModel.objects.get(id=session_year)
attendance = Attendance.objects.filter(
subject_id=subject_model, session_year_id=session_model
)
# Only Passing Student Id and Student Name Only
list_data = []
for attendance_single in attendance:
data_small = {
"id": attendance_single.id,
"attendance_date": str(attendance_single.attendance_date),
"session_year_id": attendance_single.session_year_id.id,
}
list_data.append(data_small)
return JsonResponse(
json.dumps(list_data), content_type="application/json", safe=False
)
@csrf_exempt
def get_attendance_student(request):
# Getting Values from Ajax POST 'Fetch Student'
attendance_date = request.POST.get("attendance_date")
attendance = Attendance.objects.get(id=attendance_date)
attendance_data = AttendanceReport.objects.filter(attendance_id=attendance)
# Only Passing Student Id and Student Name Only
list_data = []
for student in attendance_data:
data_small = {
"id": student.student_id.admin.id,
"name": student.student_id.admin.first_name
+ " "
+ student.student_id.admin.last_name,
"status": student.status,
}
list_data.append(data_small)
return JsonResponse(
json.dumps(list_data), content_type="application/json", safe=False
)
@csrf_exempt
def update_attendance_data(request):
student_ids = request.POST.get("student_ids")
attendance_date = request.POST.get("attendance_date")
attendance = Attendance.objects.get(id=attendance_date)
json_student = json.loads(student_ids)
try:
for stud in json_student:
# Attendance of Individual Student saved on AttendanceReport Model
student = Students.objects.get(admin=stud["id"])
attendance_report = AttendanceReport.objects.get(
student_id=student, attendance_id=attendance
)
attendance_report.status = stud["status"]
attendance_report.save()
return HttpResponse("OK")
except:
return HttpResponse("Error")
def staff_profile(request):
user = CustomUser.objects.get(id=request.user.id)
staff = Staffs.objects.get(admin=user)
context = {"user": user, "staff": staff}
return render(request, "staff_template/staff_profile.html", context)
def staff_profile_update(request):
if request.method != "POST":
messages.error(request, "Invalid Method!")
return redirect("staff_profile")
else:
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
password = request.POST.get("password")
address = request.POST.get("address")
try:
customuser = CustomUser.objects.get(id=request.user.id)
customuser.first_name = first_name
customuser.last_name = last_name
if password != None and password != "":
customuser.set_password(password)
customuser.save()
staff = Staffs.objects.get(admin=customuser.id)
staff.address = address
staff.save()
messages.success(request, "Profile Updated Successfully")
return redirect("staff_profile")
except:
messages.error(request, "Failed to Update Profile")
return redirect("staff_profile")
def staff_add_result(request):
subjects = Subjects.objects.filter(staff_id=request.user.id)
session_years = SessionYearModel.objects.all()
context = {
"subjects": subjects,
"session_years": session_years,
}
return render(request, "staff_template/add_result_template.html", context)
def staff_add_result_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("staff_add_result")
else:
student_admin_id = request.POST.get("student_list")
assignment_marks = request.POST.get("assignment_marks")
exam_marks = request.POST.get("exam_marks")
subject_id = request.POST.get("subject")
student_obj = Students.objects.get(admin=student_admin_id)
subject_obj = Subjects.objects.get(id=subject_id)
try:
# Check if Students Result Already Exists or not
check_exist = StudentResult.objects.filter(
subject_id=subject_obj, student_id=student_obj
).exists()
if check_exist:
result = StudentResult.objects.get(
subject_id=subject_obj, student_id=student_obj
)
result.subject_assignment_marks = assignment_marks
result.subject_exam_marks = exam_marks
result.save()
messages.success(request, "Result Updated Successfully!")
return redirect("staff_add_result")
else:
result = StudentResult(
student_id=student_obj,
subject_id=subject_obj,
subject_exam_marks=exam_marks,
subject_assignment_marks=assignment_marks,
)
result.save()
messages.success(request, "Result Added Successfully!")
return redirect("staff_add_result")
except:
messages.error(request, "Failed to Add Result!")
return redirect("staff_add_result") |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib import messages
from django.core.files.storage import FileSystemStorage
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
import json
from .models import (
CustomUser,
Staffs,
Courses,
Subjects,
Students,
SessionYearModel,
Attendance,
AttendanceReport,
LeaveReportStaff,
FeedBackStaffs,
StudentResult,
)
def staff_home(request):
# Fetching All Students under Staff
print(request.user.id)
subjects = Subjects.objects.filter(staff_id=request.user.id)
print(subjects)
course_id_list = []
for subject in subjects:
course = Courses.objects.get(id=subject.course_id.id)
course_id_list.append(course.id)
final_course = []
# Removing Duplicate Course Id
for course_id in course_id_list:
if course_id not in final_course:
final_course.append(course_id)
print(final_course)
students_count = Students.objects.filter(course_id__in=final_course).count()
subject_count = subjects.count()
print(subject_count)
print(students_count)
# Fetch All Attendance Count
attendance_count = Attendance.objects.filter(subject_id__in=subjects).count()
# Fetch All Approve Leave
# print(request.user)
print(request.user.user_type)
staff = Staffs.objects.get(admin=request.user.id)
leave_count = LeaveReportStaff.objects.filter(
staff_id=staff.id, leave_status=1
).count()
# Fetch Attendance Data by Subjects
subject_list = []
attendance_list = []
for subject in subjects:
attendance_count1 = Attendance.objects.filter(subject_id=subject.id).count()
subject_list.append(subject.subject_name)
attendance_list.append(attendance_count1)
students_attendance = Students.objects.filter(course_id__in=final_course)
student_list = []
student_list_attendance_present = []
student_list_attendance_absent = []
for student in students_attendance:
attendance_present_count = AttendanceReport.objects.filter(
status=True, student_id=student.id
).count()
attendance_absent_count = AttendanceReport.objects.filter(
status=False, student_id=student.id
).count()
student_list.append(student.admin.first_name + " " + student.admin.last_name)
student_list_attendance_present.append(attendance_present_count)
student_list_attendance_absent.append(attendance_absent_count)
context = {
"students_count": students_count,
"attendance_count": attendance_count,
"leave_count": leave_count,
"subject_count": subject_count,
"subject_list": subject_list,
"attendance_list": attendance_list,
"student_list": student_list,
"attendance_present_list": student_list_attendance_present,
"attendance_absent_list": student_list_attendance_absent,
}
return render(request, "staff_template/staff_home_template.html", context)
def staff_take_attendance(request):
subjects = Subjects.objects.filter(staff_id=request.user.id)
session_years = SessionYearModel.objects.all()
context = {"subjects": subjects, "session_years": session_years}
return render(request, "staff_template/take_attendance_template.html", context)
def staff_apply_leave(request):
print(request.user.id)
staff_obj = Staffs.objects.get(admin=request.user.id)
leave_data = LeaveReportStaff.objects.filter(staff_id=staff_obj)
context = {"leave_data": leave_data}
return render(request, "staff_template/staff_apply_leave_template.html", context)
def staff_apply_leave_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("staff_apply_leave")
else:
leave_date = request.POST.get("leave_date")
leave_message = request.POST.get("leave_message")
staff_obj = Staffs.objects.get(admin=request.user.id)
try:
leave_report = LeaveReportStaff(
staff_id=staff_obj,
leave_date=leave_date,
leave_message=leave_message,
leave_status=0,
)
leave_report.save()
messages.success(request, "Applied for Leave.")
return redirect("staff_apply_leave")
except:
messages.error(request, "Failed to Apply Leave")
return redirect("staff_apply_leave")
def staff_feedback(request):
return render(request, "staff_template/staff_feedback_template.html")
def staff_feedback_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method.")
return redirect("staff_feedback")
else:
feedback = request.POST.get("feedback_message")
staff_obj = Staffs.objects.get(admin=request.user.id)
try:
add_feedback = FeedBackStaffs(
staff_id=staff_obj, feedback=feedback, feedback_reply=""
)
add_feedback.save()
messages.success(request, "Feedback Sent.")
return redirect("staff_feedback")
except:
messages.error(request, "Failed to Send Feedback.")
return redirect("staff_feedback")
@csrf_exempt
def get_students(request):
subject_id = request.POST.get("subject")
session_year = request.POST.get("session_year")
# Students enroll to Course, Course has Subjects
# Getting all data from subject model based on subject_id
subject_model = Subjects.objects.get(id=subject_id)
session_model = SessionYearModel.objects.get(id=session_year)
students = Students.objects.filter(
course_id=subject_model.course_id, session_year_id=session_model
)
# Only Passing Student Id and Student Name Only
list_data = []
for student in students:
data_small = {
"id": student.admin.id,
"name": student.admin.first_name + " " + student.admin.last_name,
}
list_data.append(data_small)
return JsonResponse(
json.dumps(list_data), content_type="application/json", safe=False
)
@csrf_exempt
def save_attendance_data(request):
# Get Values from Staf Take Attendance form via AJAX (JavaScript)
# Use getlist to access HTML Array/List Input Data
student_ids = request.POST.get("student_ids")
subject_id = request.POST.get("subject_id")
attendance_date = request.POST.get("attendance_date")
session_year_id = request.POST.get("session_year_id")
subject_model = Subjects.objects.get(id=subject_id)
session_year_model = SessionYearModel.objects.get(id=session_year_id)
json_student = json.loads(student_ids)
try:
# First Attendance Data is Saved on Attendance Model
attendance = Attendance(
subject_id=subject_model,
attendance_date=attendance_date,
session_year_id=session_year_model,
)
attendance.save()
for stud in json_student:
# Attendance of Individual Student saved on AttendanceReport Model
student = Students.objects.get(admin=stud["id"])
attendance_report = AttendanceReport(
student_id=student, attendance_id=attendance, status=stud["status"]
)
attendance_report.save()
return HttpResponse("OK")
except:
return HttpResponse("Error")
def staff_update_attendance(request):
subjects = Subjects.objects.filter(staff_id=request.user.id)
session_years = SessionYearModel.objects.all()
context = {"subjects": subjects, "session_years": session_years}
return render(request, "staff_template/update_attendance_template.html", context)
@csrf_exempt
def get_attendance_dates(request):
# Getting Values from Ajax POST 'Fetch Student'
subject_id = request.POST.get("subject")
session_year = request.POST.get("session_year_id")
# Students enroll to Course, Course has Subjects
# Getting all data from subject model based on subject_id
subject_model = Subjects.objects.get(id=subject_id)
session_model = SessionYearModel.objects.get(id=session_year)
attendance = Attendance.objects.filter(
subject_id=subject_model, session_year_id=session_model
)
# Only Passing Student Id and Student Name Only
list_data = []
for attendance_single in attendance:
data_small = {
"id": attendance_single.id,
"attendance_date": str(attendance_single.attendance_date),
"session_year_id": attendance_single.session_year_id.id,
}
list_data.append(data_small)
return JsonResponse(
json.dumps(list_data), content_type="application/json", safe=False
)
@csrf_exempt
def get_attendance_student(request):
# Getting Values from Ajax POST 'Fetch Student'
attendance_date = request.POST.get("attendance_date")
attendance = Attendance.objects.get(id=attendance_date)
attendance_data = AttendanceReport.objects.filter(attendance_id=attendance)
# Only Passing Student Id and Student Name Only
list_data = []
for student in attendance_data:
data_small = {
"id": student.student_id.admin.id,
"name": student.student_id.admin.first_name
+ " "
+ student.student_id.admin.last_name,
"status": student.status,
}
list_data.append(data_small)
return JsonResponse(
json.dumps(list_data), content_type="application/json", safe=False
)
@csrf_exempt
def update_attendance_data(request):
student_ids = request.POST.get("student_ids")
attendance_date = request.POST.get("attendance_date")
attendance = Attendance.objects.get(id=attendance_date)
json_student = json.loads(student_ids)
try:
for stud in json_student:
# Attendance of Individual Student saved on AttendanceReport Model
student = Students.objects.get(admin=stud["id"])
attendance_report = AttendanceReport.objects.get(
student_id=student, attendance_id=attendance
)
attendance_report.status = stud["status"]
attendance_report.save()
return HttpResponse("OK")
except:
return HttpResponse("Error")
def staff_profile(request):
user = CustomUser.objects.get(id=request.user.id)
staff = Staffs.objects.get(admin=user)
context = {"user": user, "staff": staff}
return render(request, "staff_template/staff_profile.html", context)
def staff_profile_update(request):
if request.method != "POST":
messages.error(request, "Invalid Method!")
return redirect("staff_profile")
else:
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
password = request.POST.get("password")
address = request.POST.get("address")
try:
customuser = CustomUser.objects.get(id=request.user.id)
customuser.first_name = first_name
customuser.last_name = last_name
if password != None and password != "":
customuser.set_password(password)
customuser.save()
staff = Staffs.objects.get(admin=customuser.id)
staff.address = address
staff.save()
messages.success(request, "Profile Updated Successfully")
return redirect("staff_profile")
except:
messages.error(request, "Failed to Update Profile")
return redirect("staff_profile")
def staff_add_result(request):
subjects = Subjects.objects.filter(staff_id=request.user.id)
session_years = SessionYearModel.objects.all()
context = {
"subjects": subjects,
"session_years": session_years,
}
return render(request, "staff_template/add_result_template.html", context)
def staff_add_result_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("staff_add_result")
else:
student_admin_id = request.POST.get("student_list")
assignment_marks = request.POST.get("assignment_marks")
exam_marks = request.POST.get("exam_marks")
subject_id = request.POST.get("subject")
student_obj = Students.objects.get(admin=student_admin_id)
subject_obj = Subjects.objects.get(id=subject_id)
try:
# Check if Students Result Already Exists or not
check_exist = StudentResult.objects.filter(
subject_id=subject_obj, student_id=student_obj
).exists()
if check_exist:
result = StudentResult.objects.get(
subject_id=subject_obj, student_id=student_obj
)
result.subject_assignment_marks = assignment_marks
result.subject_exam_marks = exam_marks
result.save()
messages.success(request, "Result Updated Successfully!")
return redirect("staff_add_result")
else:
result = StudentResult(
student_id=student_obj,
subject_id=subject_obj,
subject_exam_marks=exam_marks,
subject_assignment_marks=assignment_marks,
)
result.save()
messages.success(request, "Result Added Successfully!")
return redirect("staff_add_result")
except:
messages.error(request, "Failed to Add Result!")
return redirect("staff_add_result")
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib import messages
from django.core.files.storage import FileSystemStorage
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
import json
from .forms import AddStudentForm, EditStudentForm
from .models import (
CustomUser,
Staffs,
Courses,
Subjects,
Students,
SessionYearModel,
FeedBackStudent,
FeedBackStaffs,
LeaveReportStudent,
LeaveReportStaff,
Attendance,
AttendanceReport,
)
def admin_home(request):
all_student_count = Students.objects.all().count()
subject_count = Subjects.objects.all().count()
course_count = Courses.objects.all().count()
staff_count = Staffs.objects.all().count()
course_all = Courses.objects.all()
course_name_list = []
subject_count_list = []
student_count_list_in_course = []
for course in course_all:
subjects = Subjects.objects.filter(course_id=course.id).count()
students = Students.objects.filter(course_id=course.id).count()
course_name_list.append(course.course_name)
subject_count_list.append(subjects)
student_count_list_in_course.append(students)
subject_all = Subjects.objects.all()
subject_list = []
student_count_list_in_subject = []
for subject in subject_all:
course = Courses.objects.get(id=subject.course_id.id)
student_count = Students.objects.filter(course_id=course.id).count()
subject_list.append(subject.subject_name)
student_count_list_in_subject.append(student_count)
# For Saffs
staff_attendance_present_list = []
staff_attendance_leave_list = []
staff_name_list = []
staffs = Staffs.objects.all()
for staff in staffs:
subject_ids = Subjects.objects.filter(staff_id=staff.admin.id)
attendance = Attendance.objects.filter(subject_id__in=subject_ids).count()
leaves = LeaveReportStaff.objects.filter(
staff_id=staff.id, leave_status=1
).count()
staff_attendance_present_list.append(attendance)
staff_attendance_leave_list.append(leaves)
staff_name_list.append(staff.admin.first_name)
# For Students
student_attendance_present_list = []
student_attendance_leave_list = []
student_name_list = []
students = Students.objects.all()
for student in students:
attendance = AttendanceReport.objects.filter(
student_id=student.id, status=True
).count()
absent = AttendanceReport.objects.filter(
student_id=student.id, status=False
).count()
leaves = LeaveReportStudent.objects.filter(
student_id=student.id, leave_status=1
).count()
student_attendance_present_list.append(attendance)
student_attendance_leave_list.append(leaves + absent)
student_name_list.append(student.admin.first_name)
context = {
"all_student_count": all_student_count,
"subject_count": subject_count,
"course_count": course_count,
"staff_count": staff_count,
"course_name_list": course_name_list,
"subject_count_list": subject_count_list,
"student_count_list_in_course": student_count_list_in_course,
"subject_list": subject_list,
"student_count_list_in_subject": student_count_list_in_subject,
"staff_attendance_present_list": staff_attendance_present_list,
"staff_attendance_leave_list": staff_attendance_leave_list,
"staff_name_list": staff_name_list,
"student_attendance_present_list": student_attendance_present_list,
"student_attendance_leave_list": student_attendance_leave_list,
"student_name_list": student_name_list,
}
return render(request, "hod_template/home_content.html", context)
def add_staff(request):
return render(request, "hod_template/add_staff_template.html")
def add_staff_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method ")
return redirect("add_staff")
else:
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
username = request.POST.get("username")
email = request.POST.get("email")
password = request.POST.get("password")
address = request.POST.get("address")
try:
user = CustomUser.objects.create_user(
username=username,
password=password,
email=email,
first_name=first_name,
last_name=last_name,
user_type=2,
)
user.staffs.address = address
user.save()
messages.success(request, "Staff Added Successfully!")
return redirect("add_staff")
except:
messages.error(request, "Failed to Add Staff!")
return redirect("add_staff")
def manage_staff(request):
staffs = Staffs.objects.all()
context = {"staffs": staffs}
return render(request, "hod_template/manage_staff_template.html", context)
def edit_staff(request, staff_id):
staff = Staffs.objects.get(admin=staff_id)
context = {"staff": staff, "id": staff_id}
return render(request, "hod_template/edit_staff_template.html", context)
def edit_staff_save(request):
if request.method != "POST":
return HttpResponse("<h2>Method Not Allowed</h2>")
else:
staff_id = request.POST.get("staff_id")
username = request.POST.get("username")
email = request.POST.get("email")
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
address = request.POST.get("address")
try:
# INSERTING into Customuser Model
user = CustomUser.objects.get(id=staff_id)
user.first_name = first_name
user.last_name = last_name
user.email = email
user.username = username
user.save()
# INSERTING into Staff Model
staff_model = Staffs.objects.get(admin=staff_id)
staff_model.address = address
staff_model.save()
messages.success(request, "Staff Updated Successfully.")
return redirect("/edit_staff/" + staff_id)
except:
messages.error(request, "Failed to Update Staff.")
return redirect("/edit_staff/" + staff_id)
def delete_staff(request, staff_id):
staff = Staffs.objects.get(admin=staff_id)
try:
staff.delete()
messages.success(request, "Staff Deleted Successfully.")
return redirect("manage_staff")
except:
messages.error(request, "Failed to Delete Staff.")
return redirect("manage_staff")
def add_course(request):
return render(request, "hod_template/add_course_template.html")
def add_course_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method!")
return redirect("add_course")
else:
course = request.POST.get("course")
try:
course_model = Courses(course_name=course)
course_model.save()
messages.success(request, "Course Added Successfully!")
return redirect("add_course")
except:
messages.error(request, "Failed to Add Course!")
return redirect("add_course")
def manage_course(request):
courses = Courses.objects.all()
context = {"courses": courses}
return render(request, "hod_template/manage_course_template.html", context)
def edit_course(request, course_id):
course = Courses.objects.get(id=course_id)
context = {"course": course, "id": course_id}
return render(request, "hod_template/edit_course_template.html", context)
def edit_course_save(request):
if request.method != "POST":
HttpResponse("Invalid Method")
else:
course_id = request.POST.get("course_id")
course_name = request.POST.get("course")
try:
course = Courses.objects.get(id=course_id)
course.course_name = course_name
course.save()
messages.success(request, "Course Updated Successfully.")
return redirect("/edit_course/" + course_id)
except:
messages.error(request, "Failed to Update Course.")
return redirect("/edit_course/" + course_id)
def delete_course(request, course_id):
course = Courses.objects.get(id=course_id)
try:
course.delete()
messages.success(request, "Course Deleted Successfully.")
return redirect("manage_course")
except:
messages.error(request, "Failed to Delete Course.")
return redirect("manage_course")
def manage_session(request):
session_years = SessionYearModel.objects.all()
context = {"session_years": session_years}
return render(request, "hod_template/manage_session_template.html", context)
def add_session(request):
return render(request, "hod_template/add_session_template.html")
def add_session_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("add_course")
else:
session_start_year = request.POST.get("session_start_year")
session_end_year = request.POST.get("session_end_year")
try:
sessionyear = SessionYearModel(
session_start_year=session_start_year, session_end_year=session_end_year
)
sessionyear.save()
messages.success(request, "Session Year added Successfully!")
return redirect("add_session")
except:
messages.error(request, "Failed to Add Session Year")
return redirect("add_session")
def edit_session(request, session_id):
session_year = SessionYearModel.objects.get(id=session_id)
context = {"session_year": session_year}
return render(request, "hod_template/edit_session_template.html", context)
def edit_session_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method!")
return redirect("manage_session")
else:
session_id = request.POST.get("session_id")
session_start_year = request.POST.get("session_start_year")
session_end_year = request.POST.get("session_end_year")
try:
session_year = SessionYearModel.objects.get(id=session_id)
session_year.session_start_year = session_start_year
session_year.session_end_year = session_end_year
session_year.save()
messages.success(request, "Session Year Updated Successfully.")
return redirect("/edit_session/" + session_id)
except:
messages.error(request, "Failed to Update Session Year.")
return redirect("/edit_session/" + session_id)
def delete_session(request, session_id):
session = SessionYearModel.objects.get(id=session_id)
try:
session.delete()
messages.success(request, "Session Deleted Successfully.")
return redirect("manage_session")
except:
messages.error(request, "Failed to Delete Session.")
return redirect("manage_session")
def add_student(request):
form = AddStudentForm()
context = {"form": form}
return render(request, "hod_template/add_student_template.html", context)
def add_student_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("add_student")
else:
form = AddStudentForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data["first_name"]
last_name = form.cleaned_data["last_name"]
username = form.cleaned_data["username"]
email = form.cleaned_data["email"]
password = form.cleaned_data["password"]
address = form.cleaned_data["address"]
session_year_id = form.cleaned_data["session_year_id"]
course_id = form.cleaned_data["course_id"]
gender = form.cleaned_data["gender"]
if len(request.FILES) != 0:
profile_pic = request.FILES["profile_pic"]
fs = FileSystemStorage()
filename = fs.save(profile_pic.name, profile_pic)
profile_pic_url = fs.url(filename)
else:
profile_pic_url = None
try:
user = CustomUser.objects.create_user(
username=username,
password=password,
email=email,
first_name=first_name,
last_name=last_name,
user_type=3,
)
user.students.address = address
course_obj = Courses.objects.get(id=course_id)
user.students.course_id = course_obj
session_year_obj = SessionYearModel.objects.get(id=session_year_id)
user.students.session_year_id = session_year_obj
user.students.gender = gender
user.students.profile_pic = profile_pic_url
user.save()
messages.success(request, "Student Added Successfully!")
return redirect("add_student")
except:
messages.error(request, "Failed to Add Student!")
return redirect("add_student")
else:
return redirect("add_student")
def manage_student(request):
students = Students.objects.all()
context = {"students": students}
return render(request, "hod_template/manage_student_template.html", context)
def edit_student(request, student_id):
# Adding Student ID into Session Variable
request.session["student_id"] = student_id
student = Students.objects.get(admin=student_id)
form = EditStudentForm()
# Filling the form with Data from Database
form.fields["email"].initial = student.admin.email
form.fields["username"].initial = student.admin.username
form.fields["first_name"].initial = student.admin.first_name
form.fields["last_name"].initial = student.admin.last_name
form.fields["address"].initial = student.address
form.fields["course_id"].initial = student.course_id.id
form.fields["gender"].initial = student.gender
form.fields["session_year_id"].initial = student.session_year_id.id
context = {"id": student_id, "username": student.admin.username, "form": form}
return render(request, "hod_template/edit_student_template.html", context)
def edit_student_save(request):
if request.method != "POST":
return HttpResponse("Invalid Method!")
else:
student_id = request.session.get("student_id")
if student_id == None:
return redirect("/manage_student")
form = EditStudentForm(request.POST, request.FILES)
if form.is_valid():
email = form.cleaned_data["email"]
username = form.cleaned_data["username"]
first_name = form.cleaned_data["first_name"]
last_name = form.cleaned_data["last_name"]
address = form.cleaned_data["address"]
course_id = form.cleaned_data["course_id"]
gender = form.cleaned_data["gender"]
session_year_id = form.cleaned_data["session_year_id"]
# Getting Profile Pic first
# First Check whether the file is selected or not
# Upload only if file is selected
if len(request.FILES) != 0:
profile_pic = request.FILES["profile_pic"]
fs = FileSystemStorage()
filename = fs.save(profile_pic.name, profile_pic)
profile_pic_url = fs.url(filename)
else:
profile_pic_url = None
try:
# First Update into Custom User Model
user = CustomUser.objects.get(id=student_id)
user.first_name = first_name
user.last_name = last_name
user.email = email
user.username = username
user.save()
# Then Update Students Table
student_model = Students.objects.get(admin=student_id)
student_model.address = address
course = Courses.objects.get(id=course_id)
student_model.course_id = course
session_year_obj = SessionYearModel.objects.get(id=session_year_id)
student_model.session_year_id = session_year_obj
student_model.gender = gender
if profile_pic_url != None:
student_model.profile_pic = profile_pic_url
student_model.save()
# Delete student_id SESSION after the data is updated
del request.session["student_id"]
messages.success(request, "Student Updated Successfully!")
return redirect("/edit_student/" + student_id)
except:
messages.success(request, "Failed to Uupdate Student.")
return redirect("/edit_student/" + student_id)
else:
return redirect("/edit_student/" + student_id)
def delete_student(request, student_id):
student = Students.objects.get(admin=student_id)
try:
student.delete()
messages.success(request, "Student Deleted Successfully.")
return redirect("manage_student")
except:
messages.error(request, "Failed to Delete Student.")
return redirect("manage_student")
def add_subject(request):
courses = Courses.objects.all()
staffs = CustomUser.objects.filter(user_type="2")
context = {"courses": courses, "staffs": staffs}
return render(request, "hod_template/add_subject_template.html", context)
def add_subject_save(request):
if request.method != "POST":
messages.error(request, "Method Not Allowed!")
return redirect("add_subject")
else:
subject_name = request.POST.get("subject")
course_id = request.POST.get("course")
course = Courses.objects.get(id=course_id)
staff_id = request.POST.get("staff")
staff = CustomUser.objects.get(id=staff_id)
try:
subject = Subjects(
subject_name=subject_name, course_id=course, staff_id=staff
)
subject.save()
messages.success(request, "Subject Added Successfully!")
return redirect("add_subject")
except:
messages.error(request, "Failed to Add Subject!")
return redirect("add_subject")
def manage_subject(request):
subjects = Subjects.objects.all()
context = {"subjects": subjects}
return render(request, "hod_template/manage_subject_template.html", context)
def edit_subject(request, subject_id):
subject = Subjects.objects.get(id=subject_id)
courses = Courses.objects.all()
staffs = CustomUser.objects.filter(user_type="2")
context = {
"subject": subject,
"courses": courses,
"staffs": staffs,
"id": subject_id,
}
return render(request, "hod_template/edit_subject_template.html", context)
def edit_subject_save(request):
if request.method != "POST":
HttpResponse("Invalid Method.")
else:
subject_id = request.POST.get("subject_id")
subject_name = request.POST.get("subject")
course_id = request.POST.get("course")
staff_id = request.POST.get("staff")
try:
subject = Subjects.objects.get(id=subject_id)
subject.subject_name = subject_name
course = Courses.objects.get(id=course_id)
subject.course_id = course
staff = CustomUser.objects.get(id=staff_id)
subject.staff_id = staff
subject.save()
messages.success(request, "Subject Updated Successfully.")
return HttpResponseRedirect(
reverse("edit_subject", kwargs={"subject_id": subject_id})
)
except:
messages.error(request, "Failed to Update Subject.")
return HttpResponseRedirect(
reverse("edit_subject", kwargs={"subject_id": subject_id})
)
def delete_subject(request, subject_id):
subject = Subjects.objects.get(id=subject_id)
try:
subject.delete()
messages.success(request, "Subject Deleted Successfully.")
return redirect("manage_subject")
except:
messages.error(request, "Failed to Delete Subject.")
return redirect("manage_subject")
@csrf_exempt
def check_email_exist(request):
email = request.POST.get("email")
user_obj = CustomUser.objects.filter(email=email).exists()
if user_obj:
return HttpResponse(True)
else:
return HttpResponse(False)
@csrf_exempt
def check_username_exist(request):
username = request.POST.get("username")
user_obj = CustomUser.objects.filter(username=username).exists()
if user_obj:
return HttpResponse(True)
else:
return HttpResponse(False)
def student_feedback_message(request):
feedbacks = FeedBackStudent.objects.all()
context = {"feedbacks": feedbacks}
return render(request, "hod_template/student_feedback_template.html", context)
@csrf_exempt
def student_feedback_message_reply(request):
feedback_id = request.POST.get("id")
feedback_reply = request.POST.get("reply")
try:
feedback = FeedBackStudent.objects.get(id=feedback_id)
feedback.feedback_reply = feedback_reply
feedback.save()
return HttpResponse("True")
except:
return HttpResponse("False")
def staff_feedback_message(request):
feedbacks = FeedBackStaffs.objects.all()
context = {"feedbacks": feedbacks}
return render(request, "hod_template/staff_feedback_template.html", context)
@csrf_exempt
def staff_feedback_message_reply(request):
feedback_id = request.POST.get("id")
feedback_reply = request.POST.get("reply")
try:
feedback = FeedBackStaffs.objects.get(id=feedback_id)
feedback.feedback_reply = feedback_reply
feedback.save()
return HttpResponse("True")
except:
return HttpResponse("False")
def student_leave_view(request):
leaves = LeaveReportStudent.objects.all()
context = {"leaves": leaves}
return render(request, "hod_template/student_leave_view.html", context)
def student_leave_approve(request, leave_id):
leave = LeaveReportStudent.objects.get(id=leave_id)
leave.leave_status = 1
leave.save()
return redirect("student_leave_view")
def student_leave_reject(request, leave_id):
leave = LeaveReportStudent.objects.get(id=leave_id)
leave.leave_status = 2
leave.save()
return redirect("student_leave_view")
def staff_leave_view(request):
leaves = LeaveReportStaff.objects.all()
context = {"leaves": leaves}
return render(request, "hod_template/staff_leave_view.html", context)
def staff_leave_approve(request, leave_id):
leave = LeaveReportStaff.objects.get(id=leave_id)
leave.leave_status = 1
leave.save()
return redirect("staff_leave_view")
def staff_leave_reject(request, leave_id):
leave = LeaveReportStaff.objects.get(id=leave_id)
leave.leave_status = 2
leave.save()
return redirect("staff_leave_view")
def admin_view_attendance(request):
subjects = Subjects.objects.all()
session_years = SessionYearModel.objects.all()
context = {"subjects": subjects, "session_years": session_years}
return render(request, "hod_template/admin_view_attendance.html", context)
@csrf_exempt
def admin_get_attendance_dates(request):
subject_id = request.POST.get("subject")
session_year = request.POST.get("session_year_id")
# Students enroll to Course, Course has Subjects
# Getting all data from subject model based on subject_id
subject_model = Subjects.objects.get(id=subject_id)
session_model = SessionYearModel.objects.get(id=session_year)
attendance = Attendance.objects.filter(
subject_id=subject_model, session_year_id=session_model
)
# Only Passing Student Id and Student Name Only
list_data = []
for attendance_single in attendance:
data_small = {
"id": attendance_single.id,
"attendance_date": str(attendance_single.attendance_date),
"session_year_id": attendance_single.session_year_id.id,
}
list_data.append(data_small)
return JsonResponse(
json.dumps(list_data), content_type="application/json", safe=False
)
@csrf_exempt
def admin_get_attendance_student(request):
# Getting Values from Ajax POST 'Fetch Student'
attendance_date = request.POST.get("attendance_date")
attendance = Attendance.objects.get(id=attendance_date)
attendance_data = AttendanceReport.objects.filter(attendance_id=attendance)
# Only Passing Student Id and Student Name Only
list_data = []
for student in attendance_data:
data_small = {
"id": student.student_id.admin.id,
"name": student.student_id.admin.first_name
+ " "
+ student.student_id.admin.last_name,
"status": student.status,
}
list_data.append(data_small)
return JsonResponse(
json.dumps(list_data), content_type="application/json", safe=False
)
def admin_profile(request):
user = CustomUser.objects.get(id=request.user.id)
context = {"user": user}
return render(request, "hod_template/admin_profile.html", context)
def admin_profile_update(request):
if request.method != "POST":
messages.error(request, "Invalid Method!")
return redirect("admin_profile")
else:
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
password = request.POST.get("password")
try:
customuser = CustomUser.objects.get(id=request.user.id)
customuser.first_name = first_name
customuser.last_name = last_name
if password != None and password != "":
customuser.set_password(password)
customuser.save()
messages.success(request, "Profile Updated Successfully")
return redirect("admin_profile")
except:
messages.error(request, "Failed to Update Profile")
return redirect("admin_profile")
def staff_profile(request):
pass
def student_profile(requtest):
pass |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib import messages
from django.core.files.storage import FileSystemStorage
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
import json
from .forms import AddStudentForm, EditStudentForm
from .models import (
CustomUser,
Staffs,
Courses,
Subjects,
Students,
SessionYearModel,
FeedBackStudent,
FeedBackStaffs,
LeaveReportStudent,
LeaveReportStaff,
Attendance,
AttendanceReport,
)
def admin_home(request):
all_student_count = Students.objects.all().count()
subject_count = Subjects.objects.all().count()
course_count = Courses.objects.all().count()
staff_count = Staffs.objects.all().count()
course_all = Courses.objects.all()
course_name_list = []
subject_count_list = []
student_count_list_in_course = []
for course in course_all:
subjects = Subjects.objects.filter(course_id=course.id).count()
students = Students.objects.filter(course_id=course.id).count()
course_name_list.append(course.course_name)
subject_count_list.append(subjects)
student_count_list_in_course.append(students)
subject_all = Subjects.objects.all()
subject_list = []
student_count_list_in_subject = []
for subject in subject_all:
course = Courses.objects.get(id=subject.course_id.id)
student_count = Students.objects.filter(course_id=course.id).count()
subject_list.append(subject.subject_name)
student_count_list_in_subject.append(student_count)
# For Saffs
staff_attendance_present_list = []
staff_attendance_leave_list = []
staff_name_list = []
staffs = Staffs.objects.all()
for staff in staffs:
subject_ids = Subjects.objects.filter(staff_id=staff.admin.id)
attendance = Attendance.objects.filter(subject_id__in=subject_ids).count()
leaves = LeaveReportStaff.objects.filter(
staff_id=staff.id, leave_status=1
).count()
staff_attendance_present_list.append(attendance)
staff_attendance_leave_list.append(leaves)
staff_name_list.append(staff.admin.first_name)
# For Students
student_attendance_present_list = []
student_attendance_leave_list = []
student_name_list = []
students = Students.objects.all()
for student in students:
attendance = AttendanceReport.objects.filter(
student_id=student.id, status=True
).count()
absent = AttendanceReport.objects.filter(
student_id=student.id, status=False
).count()
leaves = LeaveReportStudent.objects.filter(
student_id=student.id, leave_status=1
).count()
student_attendance_present_list.append(attendance)
student_attendance_leave_list.append(leaves + absent)
student_name_list.append(student.admin.first_name)
context = {
"all_student_count": all_student_count,
"subject_count": subject_count,
"course_count": course_count,
"staff_count": staff_count,
"course_name_list": course_name_list,
"subject_count_list": subject_count_list,
"student_count_list_in_course": student_count_list_in_course,
"subject_list": subject_list,
"student_count_list_in_subject": student_count_list_in_subject,
"staff_attendance_present_list": staff_attendance_present_list,
"staff_attendance_leave_list": staff_attendance_leave_list,
"staff_name_list": staff_name_list,
"student_attendance_present_list": student_attendance_present_list,
"student_attendance_leave_list": student_attendance_leave_list,
"student_name_list": student_name_list,
}
return render(request, "hod_template/home_content.html", context)
def add_staff(request):
return render(request, "hod_template/add_staff_template.html")
def add_staff_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method ")
return redirect("add_staff")
else:
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
username = request.POST.get("username")
email = request.POST.get("email")
password = request.POST.get("password")
address = request.POST.get("address")
try:
user = CustomUser.objects.create_user(
username=username,
password=password,
email=email,
first_name=first_name,
last_name=last_name,
user_type=2,
)
user.staffs.address = address
user.save()
messages.success(request, "Staff Added Successfully!")
return redirect("add_staff")
except:
messages.error(request, "Failed to Add Staff!")
return redirect("add_staff")
def manage_staff(request):
staffs = Staffs.objects.all()
context = {"staffs": staffs}
return render(request, "hod_template/manage_staff_template.html", context)
def edit_staff(request, staff_id):
staff = Staffs.objects.get(admin=staff_id)
context = {"staff": staff, "id": staff_id}
return render(request, "hod_template/edit_staff_template.html", context)
def edit_staff_save(request):
if request.method != "POST":
return HttpResponse("<h2>Method Not Allowed</h2>")
else:
staff_id = request.POST.get("staff_id")
username = request.POST.get("username")
email = request.POST.get("email")
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
address = request.POST.get("address")
try:
# INSERTING into Customuser Model
user = CustomUser.objects.get(id=staff_id)
user.first_name = first_name
user.last_name = last_name
user.email = email
user.username = username
user.save()
# INSERTING into Staff Model
staff_model = Staffs.objects.get(admin=staff_id)
staff_model.address = address
staff_model.save()
messages.success(request, "Staff Updated Successfully.")
return redirect("/edit_staff/" + staff_id)
except:
messages.error(request, "Failed to Update Staff.")
return redirect("/edit_staff/" + staff_id)
def delete_staff(request, staff_id):
staff = Staffs.objects.get(admin=staff_id)
try:
staff.delete()
messages.success(request, "Staff Deleted Successfully.")
return redirect("manage_staff")
except:
messages.error(request, "Failed to Delete Staff.")
return redirect("manage_staff")
def add_course(request):
return render(request, "hod_template/add_course_template.html")
def add_course_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method!")
return redirect("add_course")
else:
course = request.POST.get("course")
try:
course_model = Courses(course_name=course)
course_model.save()
messages.success(request, "Course Added Successfully!")
return redirect("add_course")
except:
messages.error(request, "Failed to Add Course!")
return redirect("add_course")
def manage_course(request):
courses = Courses.objects.all()
context = {"courses": courses}
return render(request, "hod_template/manage_course_template.html", context)
def edit_course(request, course_id):
course = Courses.objects.get(id=course_id)
context = {"course": course, "id": course_id}
return render(request, "hod_template/edit_course_template.html", context)
def edit_course_save(request):
if request.method != "POST":
HttpResponse("Invalid Method")
else:
course_id = request.POST.get("course_id")
course_name = request.POST.get("course")
try:
course = Courses.objects.get(id=course_id)
course.course_name = course_name
course.save()
messages.success(request, "Course Updated Successfully.")
return redirect("/edit_course/" + course_id)
except:
messages.error(request, "Failed to Update Course.")
return redirect("/edit_course/" + course_id)
def delete_course(request, course_id):
course = Courses.objects.get(id=course_id)
try:
course.delete()
messages.success(request, "Course Deleted Successfully.")
return redirect("manage_course")
except:
messages.error(request, "Failed to Delete Course.")
return redirect("manage_course")
def manage_session(request):
session_years = SessionYearModel.objects.all()
context = {"session_years": session_years}
return render(request, "hod_template/manage_session_template.html", context)
def add_session(request):
return render(request, "hod_template/add_session_template.html")
def add_session_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("add_course")
else:
session_start_year = request.POST.get("session_start_year")
session_end_year = request.POST.get("session_end_year")
try:
sessionyear = SessionYearModel(
session_start_year=session_start_year, session_end_year=session_end_year
)
sessionyear.save()
messages.success(request, "Session Year added Successfully!")
return redirect("add_session")
except:
messages.error(request, "Failed to Add Session Year")
return redirect("add_session")
def edit_session(request, session_id):
session_year = SessionYearModel.objects.get(id=session_id)
context = {"session_year": session_year}
return render(request, "hod_template/edit_session_template.html", context)
def edit_session_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method!")
return redirect("manage_session")
else:
session_id = request.POST.get("session_id")
session_start_year = request.POST.get("session_start_year")
session_end_year = request.POST.get("session_end_year")
try:
session_year = SessionYearModel.objects.get(id=session_id)
session_year.session_start_year = session_start_year
session_year.session_end_year = session_end_year
session_year.save()
messages.success(request, "Session Year Updated Successfully.")
return redirect("/edit_session/" + session_id)
except:
messages.error(request, "Failed to Update Session Year.")
return redirect("/edit_session/" + session_id)
def delete_session(request, session_id):
session = SessionYearModel.objects.get(id=session_id)
try:
session.delete()
messages.success(request, "Session Deleted Successfully.")
return redirect("manage_session")
except:
messages.error(request, "Failed to Delete Session.")
return redirect("manage_session")
def add_student(request):
form = AddStudentForm()
context = {"form": form}
return render(request, "hod_template/add_student_template.html", context)
def add_student_save(request):
if request.method != "POST":
messages.error(request, "Invalid Method")
return redirect("add_student")
else:
form = AddStudentForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data["first_name"]
last_name = form.cleaned_data["last_name"]
username = form.cleaned_data["username"]
email = form.cleaned_data["email"]
password = form.cleaned_data["password"]
address = form.cleaned_data["address"]
session_year_id = form.cleaned_data["session_year_id"]
course_id = form.cleaned_data["course_id"]
gender = form.cleaned_data["gender"]
if len(request.FILES) != 0:
profile_pic = request.FILES["profile_pic"]
fs = FileSystemStorage()
filename = fs.save(profile_pic.name, profile_pic)
profile_pic_url = fs.url(filename)
else:
profile_pic_url = None
try:
user = CustomUser.objects.create_user(
username=username,
password=password,
email=email,
first_name=first_name,
last_name=last_name,
user_type=3,
)
user.students.address = address
course_obj = Courses.objects.get(id=course_id)
user.students.course_id = course_obj
session_year_obj = SessionYearModel.objects.get(id=session_year_id)
user.students.session_year_id = session_year_obj
user.students.gender = gender
user.students.profile_pic = profile_pic_url
user.save()
messages.success(request, "Student Added Successfully!")
return redirect("add_student")
except:
messages.error(request, "Failed to Add Student!")
return redirect("add_student")
else:
return redirect("add_student")
def manage_student(request):
students = Students.objects.all()
context = {"students": students}
return render(request, "hod_template/manage_student_template.html", context)
def edit_student(request, student_id):
# Adding Student ID into Session Variable
request.session["student_id"] = student_id
student = Students.objects.get(admin=student_id)
form = EditStudentForm()
# Filling the form with Data from Database
form.fields["email"].initial = student.admin.email
form.fields["username"].initial = student.admin.username
form.fields["first_name"].initial = student.admin.first_name
form.fields["last_name"].initial = student.admin.last_name
form.fields["address"].initial = student.address
form.fields["course_id"].initial = student.course_id.id
form.fields["gender"].initial = student.gender
form.fields["session_year_id"].initial = student.session_year_id.id
context = {"id": student_id, "username": student.admin.username, "form": form}
return render(request, "hod_template/edit_student_template.html", context)
def edit_student_save(request):
if request.method != "POST":
return HttpResponse("Invalid Method!")
else:
student_id = request.session.get("student_id")
if student_id == None:
return redirect("/manage_student")
form = EditStudentForm(request.POST, request.FILES)
if form.is_valid():
email = form.cleaned_data["email"]
username = form.cleaned_data["username"]
first_name = form.cleaned_data["first_name"]
last_name = form.cleaned_data["last_name"]
address = form.cleaned_data["address"]
course_id = form.cleaned_data["course_id"]
gender = form.cleaned_data["gender"]
session_year_id = form.cleaned_data["session_year_id"]
# Getting Profile Pic first
# First Check whether the file is selected or not
# Upload only if file is selected
if len(request.FILES) != 0:
profile_pic = request.FILES["profile_pic"]
fs = FileSystemStorage()
filename = fs.save(profile_pic.name, profile_pic)
profile_pic_url = fs.url(filename)
else:
profile_pic_url = None
try:
# First Update into Custom User Model
user = CustomUser.objects.get(id=student_id)
user.first_name = first_name
user.last_name = last_name
user.email = email
user.username = username
user.save()
# Then Update Students Table
student_model = Students.objects.get(admin=student_id)
student_model.address = address
course = Courses.objects.get(id=course_id)
student_model.course_id = course
session_year_obj = SessionYearModel.objects.get(id=session_year_id)
student_model.session_year_id = session_year_obj
student_model.gender = gender
if profile_pic_url != None:
student_model.profile_pic = profile_pic_url
student_model.save()
# Delete student_id SESSION after the data is updated
del request.session["student_id"]
messages.success(request, "Student Updated Successfully!")
return redirect("/edit_student/" + student_id)
except:
messages.success(request, "Failed to Uupdate Student.")
return redirect("/edit_student/" + student_id)
else:
return redirect("/edit_student/" + student_id)
def delete_student(request, student_id):
student = Students.objects.get(admin=student_id)
try:
student.delete()
messages.success(request, "Student Deleted Successfully.")
return redirect("manage_student")
except:
messages.error(request, "Failed to Delete Student.")
return redirect("manage_student")
def add_subject(request):
courses = Courses.objects.all()
staffs = CustomUser.objects.filter(user_type="2")
context = {"courses": courses, "staffs": staffs}
return render(request, "hod_template/add_subject_template.html", context)
def add_subject_save(request):
if request.method != "POST":
messages.error(request, "Method Not Allowed!")
return redirect("add_subject")
else:
subject_name = request.POST.get("subject")
course_id = request.POST.get("course")
course = Courses.objects.get(id=course_id)
staff_id = request.POST.get("staff")
staff = CustomUser.objects.get(id=staff_id)
try:
subject = Subjects(
subject_name=subject_name, course_id=course, staff_id=staff
)
subject.save()
messages.success(request, "Subject Added Successfully!")
return redirect("add_subject")
except:
messages.error(request, "Failed to Add Subject!")
return redirect("add_subject")
def manage_subject(request):
subjects = Subjects.objects.all()
context = {"subjects": subjects}
return render(request, "hod_template/manage_subject_template.html", context)
def edit_subject(request, subject_id):
subject = Subjects.objects.get(id=subject_id)
courses = Courses.objects.all()
staffs = CustomUser.objects.filter(user_type="2")
context = {
"subject": subject,
"courses": courses,
"staffs": staffs,
"id": subject_id,
}
return render(request, "hod_template/edit_subject_template.html", context)
def edit_subject_save(request):
if request.method != "POST":
HttpResponse("Invalid Method.")
else:
subject_id = request.POST.get("subject_id")
subject_name = request.POST.get("subject")
course_id = request.POST.get("course")
staff_id = request.POST.get("staff")
try:
subject = Subjects.objects.get(id=subject_id)
subject.subject_name = subject_name
course = Courses.objects.get(id=course_id)
subject.course_id = course
staff = CustomUser.objects.get(id=staff_id)
subject.staff_id = staff
subject.save()
messages.success(request, "Subject Updated Successfully.")
return HttpResponseRedirect(
reverse("edit_subject", kwargs={"subject_id": subject_id})
)
except:
messages.error(request, "Failed to Update Subject.")
return HttpResponseRedirect(
reverse("edit_subject", kwargs={"subject_id": subject_id})
)
def delete_subject(request, subject_id):
subject = Subjects.objects.get(id=subject_id)
try:
subject.delete()
messages.success(request, "Subject Deleted Successfully.")
return redirect("manage_subject")
except:
messages.error(request, "Failed to Delete Subject.")
return redirect("manage_subject")
@csrf_exempt
def check_email_exist(request):
email = request.POST.get("email")
user_obj = CustomUser.objects.filter(email=email).exists()
if user_obj:
return HttpResponse(True)
else:
return HttpResponse(False)
@csrf_exempt
def check_username_exist(request):
username = request.POST.get("username")
user_obj = CustomUser.objects.filter(username=username).exists()
if user_obj:
return HttpResponse(True)
else:
return HttpResponse(False)
def student_feedback_message(request):
feedbacks = FeedBackStudent.objects.all()
context = {"feedbacks": feedbacks}
return render(request, "hod_template/student_feedback_template.html", context)
@csrf_exempt
def student_feedback_message_reply(request):
feedback_id = request.POST.get("id")
feedback_reply = request.POST.get("reply")
try:
feedback = FeedBackStudent.objects.get(id=feedback_id)
feedback.feedback_reply = feedback_reply
feedback.save()
return HttpResponse("True")
except:
return HttpResponse("False")
def staff_feedback_message(request):
feedbacks = FeedBackStaffs.objects.all()
context = {"feedbacks": feedbacks}
return render(request, "hod_template/staff_feedback_template.html", context)
@csrf_exempt
def staff_feedback_message_reply(request):
feedback_id = request.POST.get("id")
feedback_reply = request.POST.get("reply")
try:
feedback = FeedBackStaffs.objects.get(id=feedback_id)
feedback.feedback_reply = feedback_reply
feedback.save()
return HttpResponse("True")
except:
return HttpResponse("False")
def student_leave_view(request):
leaves = LeaveReportStudent.objects.all()
context = {"leaves": leaves}
return render(request, "hod_template/student_leave_view.html", context)
def student_leave_approve(request, leave_id):
leave = LeaveReportStudent.objects.get(id=leave_id)
leave.leave_status = 1
leave.save()
return redirect("student_leave_view")
def student_leave_reject(request, leave_id):
leave = LeaveReportStudent.objects.get(id=leave_id)
leave.leave_status = 2
leave.save()
return redirect("student_leave_view")
def staff_leave_view(request):
leaves = LeaveReportStaff.objects.all()
context = {"leaves": leaves}
return render(request, "hod_template/staff_leave_view.html", context)
def staff_leave_approve(request, leave_id):
leave = LeaveReportStaff.objects.get(id=leave_id)
leave.leave_status = 1
leave.save()
return redirect("staff_leave_view")
def staff_leave_reject(request, leave_id):
leave = LeaveReportStaff.objects.get(id=leave_id)
leave.leave_status = 2
leave.save()
return redirect("staff_leave_view")
def admin_view_attendance(request):
subjects = Subjects.objects.all()
session_years = SessionYearModel.objects.all()
context = {"subjects": subjects, "session_years": session_years}
return render(request, "hod_template/admin_view_attendance.html", context)
@csrf_exempt
def admin_get_attendance_dates(request):
subject_id = request.POST.get("subject")
session_year = request.POST.get("session_year_id")
# Students enroll to Course, Course has Subjects
# Getting all data from subject model based on subject_id
subject_model = Subjects.objects.get(id=subject_id)
session_model = SessionYearModel.objects.get(id=session_year)
attendance = Attendance.objects.filter(
subject_id=subject_model, session_year_id=session_model
)
# Only Passing Student Id and Student Name Only
list_data = []
for attendance_single in attendance:
data_small = {
"id": attendance_single.id,
"attendance_date": str(attendance_single.attendance_date),
"session_year_id": attendance_single.session_year_id.id,
}
list_data.append(data_small)
return JsonResponse(
json.dumps(list_data), content_type="application/json", safe=False
)
@csrf_exempt
def admin_get_attendance_student(request):
# Getting Values from Ajax POST 'Fetch Student'
attendance_date = request.POST.get("attendance_date")
attendance = Attendance.objects.get(id=attendance_date)
attendance_data = AttendanceReport.objects.filter(attendance_id=attendance)
# Only Passing Student Id and Student Name Only
list_data = []
for student in attendance_data:
data_small = {
"id": student.student_id.admin.id,
"name": student.student_id.admin.first_name
+ " "
+ student.student_id.admin.last_name,
"status": student.status,
}
list_data.append(data_small)
return JsonResponse(
json.dumps(list_data), content_type="application/json", safe=False
)
def admin_profile(request):
user = CustomUser.objects.get(id=request.user.id)
context = {"user": user}
return render(request, "hod_template/admin_profile.html", context)
def admin_profile_update(request):
if request.method != "POST":
messages.error(request, "Invalid Method!")
return redirect("admin_profile")
else:
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
password = request.POST.get("password")
try:
customuser = CustomUser.objects.get(id=request.user.id)
customuser.first_name = first_name
customuser.last_name = last_name
if password != None and password != "":
customuser.set_password(password)
customuser.save()
messages.success(request, "Profile Updated Successfully")
return redirect("admin_profile")
except:
messages.error(request, "Failed to Update Profile")
return redirect("admin_profile")
def staff_profile(request):
pass
def student_profile(requtest):
pass
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class SessionYearModel(models.Model):
id = models.AutoField(primary_key=True)
session_start_year = models.DateField()
session_end_year = models.DateField()
objects = models.Manager()
# Overriding the Default Django Auth
# User and adding One More Field (user_type)
class CustomUser(AbstractUser):
HOD = "1"
STAFF = "2"
STUDENT = "3"
EMAIL_TO_USER_TYPE_MAP = {"hod": HOD, "staff": STAFF, "student": STUDENT}
user_type_data = ((HOD, "HOD"), (STAFF, "Staff"), (STUDENT, "Student"))
user_type = models.CharField(default=1, choices=user_type_data, max_length=10)
class AdminHOD(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Staffs(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
address = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Courses(models.Model):
id = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Subjects(models.Model):
id = models.AutoField(primary_key=True)
subject_name = models.CharField(max_length=255)
# need to give default course
course_id = models.ForeignKey(Courses, on_delete=models.CASCADE, default=1)
staff_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Students(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
gender = models.CharField(max_length=50)
profile_pic = models.FileField()
address = models.TextField()
course_id = models.ForeignKey(Courses, on_delete=models.DO_NOTHING, default=1)
session_year_id = models.ForeignKey(
SessionYearModel, null=True, on_delete=models.CASCADE
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Attendance(models.Model):
# Subject Attendance
id = models.AutoField(primary_key=True)
subject_id = models.ForeignKey(Subjects, on_delete=models.DO_NOTHING)
attendance_date = models.DateField()
session_year_id = models.ForeignKey(SessionYearModel, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class AttendanceReport(models.Model):
# Individual Student Attendance
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.DO_NOTHING)
attendance_id = models.ForeignKey(Attendance, on_delete=models.CASCADE)
status = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class LeaveReportStudent(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
leave_date = models.CharField(max_length=255)
leave_message = models.TextField()
leave_status = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class LeaveReportStaff(models.Model):
id = models.AutoField(primary_key=True)
staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
leave_date = models.CharField(max_length=255)
leave_message = models.TextField()
leave_status = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class FeedBackStudent(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
feedback = models.TextField()
feedback_reply = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class FeedBackStaffs(models.Model):
id = models.AutoField(primary_key=True)
staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
feedback = models.TextField()
feedback_reply = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class NotificationStudent(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class NotificationStaffs(models.Model):
id = models.AutoField(primary_key=True)
stafff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class StudentResult(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
subject_id = models.ForeignKey(Subjects, on_delete=models.CASCADE, default=1)
subject_exam_marks = models.FloatField(default=0)
subject_assignment_marks = models.FloatField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
# Creating Django Signals
@receiver(post_save, sender=CustomUser)
# Now Creating a Function which will
# automatically insert data in HOD, Staff or Student
def create_user_profile(sender, instance, created, **kwargs):
# if Created is true (Means Data Inserted)
if created:
# Check the user_type and insert the data in respective tables
if instance.user_type == 1:
AdminHOD.objects.create(admin=instance)
if instance.user_type == 2:
Staffs.objects.create(admin=instance)
if instance.user_type == 3:
Students.objects.create(
admin=instance,
course_id=Courses.objects.get(id=1),
session_year_id=SessionYearModel.objects.get(id=1),
address="",
profile_pic="",
gender="",
)
@receiver(post_save, sender=CustomUser)
def save_user_profile(sender, instance, **kwargs):
if instance.user_type == 1:
instance.adminhod.save()
if instance.user_type == 2:
instance.staffs.save()
if instance.user_type == 3:
instance.students.save() |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class SessionYearModel(models.Model):
id = models.AutoField(primary_key=True)
session_start_year = models.DateField()
session_end_year = models.DateField()
objects = models.Manager()
# Overriding the Default Django Auth
# User and adding One More Field (user_type)
class CustomUser(AbstractUser):
HOD = "1"
STAFF = "2"
STUDENT = "3"
EMAIL_TO_USER_TYPE_MAP = {"hod": HOD, "staff": STAFF, "student": STUDENT}
user_type_data = ((HOD, "HOD"), (STAFF, "Staff"), (STUDENT, "Student"))
user_type = models.CharField(default=1, choices=user_type_data, max_length=10)
class AdminHOD(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Staffs(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
address = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Courses(models.Model):
id = models.AutoField(primary_key=True)
course_name = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Subjects(models.Model):
id = models.AutoField(primary_key=True)
subject_name = models.CharField(max_length=255)
# need to give default course
course_id = models.ForeignKey(Courses, on_delete=models.CASCADE, default=1)
staff_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Students(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
gender = models.CharField(max_length=50)
profile_pic = models.FileField()
address = models.TextField()
course_id = models.ForeignKey(Courses, on_delete=models.DO_NOTHING, default=1)
session_year_id = models.ForeignKey(
SessionYearModel, null=True, on_delete=models.CASCADE
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Attendance(models.Model):
# Subject Attendance
id = models.AutoField(primary_key=True)
subject_id = models.ForeignKey(Subjects, on_delete=models.DO_NOTHING)
attendance_date = models.DateField()
session_year_id = models.ForeignKey(SessionYearModel, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class AttendanceReport(models.Model):
# Individual Student Attendance
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.DO_NOTHING)
attendance_id = models.ForeignKey(Attendance, on_delete=models.CASCADE)
status = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class LeaveReportStudent(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
leave_date = models.CharField(max_length=255)
leave_message = models.TextField()
leave_status = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class LeaveReportStaff(models.Model):
id = models.AutoField(primary_key=True)
staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
leave_date = models.CharField(max_length=255)
leave_message = models.TextField()
leave_status = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class FeedBackStudent(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
feedback = models.TextField()
feedback_reply = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class FeedBackStaffs(models.Model):
id = models.AutoField(primary_key=True)
staff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
feedback = models.TextField()
feedback_reply = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class NotificationStudent(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class NotificationStaffs(models.Model):
id = models.AutoField(primary_key=True)
stafff_id = models.ForeignKey(Staffs, on_delete=models.CASCADE)
message = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class StudentResult(models.Model):
id = models.AutoField(primary_key=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
subject_id = models.ForeignKey(Subjects, on_delete=models.CASCADE, default=1)
subject_exam_marks = models.FloatField(default=0)
subject_assignment_marks = models.FloatField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
# Creating Django Signals
@receiver(post_save, sender=CustomUser)
# Now Creating a Function which will
# automatically insert data in HOD, Staff or Student
def create_user_profile(sender, instance, created, **kwargs):
# if Created is true (Means Data Inserted)
if created:
# Check the user_type and insert the data in respective tables
if instance.user_type == 1:
AdminHOD.objects.create(admin=instance)
if instance.user_type == 2:
Staffs.objects.create(admin=instance)
if instance.user_type == 3:
Students.objects.create(
admin=instance,
course_id=Courses.objects.get(id=1),
session_year_id=SessionYearModel.objects.get(id=1),
address="",
profile_pic="",
gender="",
)
@receiver(post_save, sender=CustomUser)
def save_user_profile(sender, instance, **kwargs):
if instance.user_type == 1:
instance.adminhod.save()
if instance.user_type == 2:
instance.staffs.save()
if instance.user_type == 3:
instance.students.save()
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | from django import forms
from .models import Courses, SessionYearModel
class DateInput(forms.DateInput):
input_type = "date"
class AddStudentForm(forms.Form):
email = forms.EmailField(
label="Email",
max_length=50,
widget=forms.EmailInput(attrs={"class": "form-control"}),
)
password = forms.CharField(
label="Password",
max_length=50,
widget=forms.PasswordInput(attrs={"class": "form-control"}),
)
first_name = forms.CharField(
label="First Name",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
last_name = forms.CharField(
label="Last Name",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
username = forms.CharField(
label="Username",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
address = forms.CharField(
label="Address",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
# For Displaying Courses
try:
courses = Courses.objects.all()
course_list = []
for course in courses:
single_course = (course.id, course.course_name)
course_list.append(single_course)
except:
print("here")
course_list = []
# For Displaying Session Years
try:
session_years = SessionYearModel.objects.all()
session_year_list = []
for session_year in session_years:
single_session_year = (
session_year.id,
str(session_year.session_start_year)
+ " to "
+ str(session_year.session_end_year),
)
session_year_list.append(single_session_year)
except:
session_year_list = []
gender_list = (("Male", "Male"), ("Female", "Female"))
course_id = forms.ChoiceField(
label="Course",
choices=course_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
gender = forms.ChoiceField(
label="Gender",
choices=gender_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
session_year_id = forms.ChoiceField(
label="Session Year",
choices=session_year_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
profile_pic = forms.FileField(
label="Profile Pic",
required=False,
widget=forms.FileInput(attrs={"class": "form-control"}),
)
class EditStudentForm(forms.Form):
email = forms.EmailField(
label="Email",
max_length=50,
widget=forms.EmailInput(attrs={"class": "form-control"}),
)
first_name = forms.CharField(
label="First Name",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
last_name = forms.CharField(
label="Last Name",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
username = forms.CharField(
label="Username",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
address = forms.CharField(
label="Address",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
# For Displaying Courses
try:
courses = Courses.objects.all()
course_list = []
for course in courses:
single_course = (course.id, course.course_name)
course_list.append(single_course)
except:
course_list = []
# For Displaying Session Years
try:
session_years = SessionYearModel.objects.all()
session_year_list = []
for session_year in session_years:
single_session_year = (
session_year.id,
str(session_year.session_start_year)
+ " to "
+ str(session_year.session_end_year),
)
session_year_list.append(single_session_year)
except:
session_year_list = []
gender_list = (("Male", "Male"), ("Female", "Female"))
course_id = forms.ChoiceField(
label="Course",
choices=course_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
gender = forms.ChoiceField(
label="Gender",
choices=gender_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
session_year_id = forms.ChoiceField(
label="Session Year",
choices=session_year_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
profile_pic = forms.FileField(
label="Profile Pic",
required=False,
widget=forms.FileInput(attrs={"class": "form-control"}),
) |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
from django import forms
from .models import Courses, SessionYearModel
class DateInput(forms.DateInput):
input_type = "date"
class AddStudentForm(forms.Form):
email = forms.EmailField(
label="Email",
max_length=50,
widget=forms.EmailInput(attrs={"class": "form-control"}),
)
password = forms.CharField(
label="Password",
max_length=50,
widget=forms.PasswordInput(attrs={"class": "form-control"}),
)
first_name = forms.CharField(
label="First Name",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
last_name = forms.CharField(
label="Last Name",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
username = forms.CharField(
label="Username",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
address = forms.CharField(
label="Address",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
# For Displaying Courses
try:
courses = Courses.objects.all()
course_list = []
for course in courses:
single_course = (course.id, course.course_name)
course_list.append(single_course)
except:
print("here")
course_list = []
# For Displaying Session Years
try:
session_years = SessionYearModel.objects.all()
session_year_list = []
for session_year in session_years:
single_session_year = (
session_year.id,
str(session_year.session_start_year)
+ " to "
+ str(session_year.session_end_year),
)
session_year_list.append(single_session_year)
except:
session_year_list = []
gender_list = (("Male", "Male"), ("Female", "Female"))
course_id = forms.ChoiceField(
label="Course",
choices=course_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
gender = forms.ChoiceField(
label="Gender",
choices=gender_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
session_year_id = forms.ChoiceField(
label="Session Year",
choices=session_year_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
profile_pic = forms.FileField(
label="Profile Pic",
required=False,
widget=forms.FileInput(attrs={"class": "form-control"}),
)
class EditStudentForm(forms.Form):
email = forms.EmailField(
label="Email",
max_length=50,
widget=forms.EmailInput(attrs={"class": "form-control"}),
)
first_name = forms.CharField(
label="First Name",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
last_name = forms.CharField(
label="Last Name",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
username = forms.CharField(
label="Username",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
address = forms.CharField(
label="Address",
max_length=50,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
# For Displaying Courses
try:
courses = Courses.objects.all()
course_list = []
for course in courses:
single_course = (course.id, course.course_name)
course_list.append(single_course)
except:
course_list = []
# For Displaying Session Years
try:
session_years = SessionYearModel.objects.all()
session_year_list = []
for session_year in session_years:
single_session_year = (
session_year.id,
str(session_year.session_start_year)
+ " to "
+ str(session_year.session_end_year),
)
session_year_list.append(single_session_year)
except:
session_year_list = []
gender_list = (("Male", "Male"), ("Female", "Female"))
course_id = forms.ChoiceField(
label="Course",
choices=course_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
gender = forms.ChoiceField(
label="Gender",
choices=gender_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
session_year_id = forms.ChoiceField(
label="Session Year",
choices=session_year_list,
widget=forms.Select(attrs={"class": "form-control"}),
)
profile_pic = forms.FileField(
label="Profile Pic",
required=False,
widget=forms.FileInput(attrs={"class": "form-control"}),
)
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import (
CustomUser,
AdminHOD,
Staffs,
Courses,
Subjects,
Students,
Attendance,
AttendanceReport,
LeaveReportStudent,
LeaveReportStaff,
FeedBackStudent,
FeedBackStaffs,
NotificationStudent,
NotificationStaffs,
)
# Register your models here.
class UserModel(UserAdmin):
pass
admin.site.register(CustomUser, UserModel)
admin.site.register(AdminHOD)
admin.site.register(Staffs)
admin.site.register(Courses)
admin.site.register(Subjects)
admin.site.register(Students)
admin.site.register(Attendance)
admin.site.register(AttendanceReport)
admin.site.register(LeaveReportStudent)
admin.site.register(LeaveReportStaff)
admin.site.register(FeedBackStudent)
admin.site.register(FeedBackStaffs)
admin.site.register(NotificationStudent)
admin.site.register(NotificationStaffs) |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import (
CustomUser,
AdminHOD,
Staffs,
Courses,
Subjects,
Students,
Attendance,
AttendanceReport,
LeaveReportStudent,
LeaveReportStaff,
FeedBackStudent,
FeedBackStaffs,
NotificationStudent,
NotificationStaffs,
)
# Register your models here.
class UserModel(UserAdmin):
pass
admin.site.register(CustomUser, UserModel)
admin.site.register(AdminHOD)
admin.site.register(Staffs)
admin.site.register(Courses)
admin.site.register(Subjects)
admin.site.register(Students)
admin.site.register(Attendance)
admin.site.register(AttendanceReport)
admin.site.register(LeaveReportStudent)
admin.site.register(LeaveReportStaff)
admin.site.register(FeedBackStudent)
admin.site.register(FeedBackStaffs)
admin.site.register(NotificationStudent)
admin.site.register(NotificationStaffs)
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | {% load static %}??????<!DOCTYPE html><html><head>????????????<m"utf-8">????????????<meta htt"X-UA-Compatible" content="IE=edge">????????????<title>College Management System | Dashboard</title>????????????<!-- Tell the browser to be responsive to screen width --"viewport" content="width=device-width, initial-scale=1">????????????<me"viewport" content="width=device-width, initial-scale=1">????????????<!-- Font Awesome -->??????"stylesheet" href="{% static "fontawesome-free/css/all.min.css" %}">????????????<!-- Ionicons -->??????????????????????????????????????????<"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">????????????????"stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">????????????<!-- Tempusdominus Bbootstrap 4 -->??????"stylesheet" href="{% static 'tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css' %}">????????????<!-- iCheck -->??????"stylesheet" href="{% static "icheck-bootstrap/icheck-bootstrap.min.css" %}">????????????<!-- JQVMap -->??????"stylesheet" href="{% static "jqvmap/jqvmap.min.css" %}">????????????<!-- Theme style -->??????"stylesheet" href="{% static 'dist/css/adminlte.min.css'?????">????????????<!-- overlayScrollbars -->??????"stylesheet" href="{% static "overlayScrollbars/css/OverlayScrollbars.min.css" %}">????????????<!-- Daterange picker -->??????"stylesheet" href="{% static "daterangepicker/daterangepicker.css" %}">????????????<!-- summernote -->??????"stylesheet" href="{% static "summernote/summernote-bs4.css" %}">????????????<!-- Google Font: Source Sans Pro -->???????"https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">??????</head>??????????????????{% block content %}????????????{% endblock content %}??????<!-- jQuery -->????????????????????????<!-- Optional JavaScript -->????????????????????????<!-- jQuery firs"https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>????????????????????"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>????????????????????"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>??????<script "{% static "jquery/jquery.min.js"?? %}"></script><!-- jQuery UI 1.11.4 --><script src="{% static "jquery-ui/jquery-ui.min.js"?? %}"></script><!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --><script>????????????$.widget.bridge('uibutton', $.ui.button)</script><!-- Bootstrap 4 --><scr"{% static "bootstrap/js/bootstrap.bundle.min.js"?? %}"></script><!-- ChartJS --><script src="{% static "chart.js/Chart.min.js"?? %}"></script><!-- Sparkline --><script src="{% static "sparklines/sparkline.js"?? %}"></script><!-- JQVMap --><script src="{% static "jqvmap/jquery.vmap.min.js"?? %}"></script><script src="{% static "jqvmap/maps/jquery.vmap.usa.js"?? %}"></script><!-- jQuery Knob Chart --><script src="{% static "jquery-knob/jquery.knob.min.js"?? %}"></script><!-- daterangepicker --><script src="{% static "moment/moment.min.js"?? %}"></script><script src="{% static "daterangepicker/daterangepicker.js"?? %}"></script><!-- Tempusdominus Bootstrap 4 --><script src="{% static "tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"?? %}"></script><!-- Summernote --><script src="{% static "summernote/summernote-bs4.min.js"?? %}"></script><!-- overlayScrollbars --><script src="{% static "overlayScrollbars/js/jquery.overlayScrollbars.min.js"?? %}"></script><!-- AdminLTE App --><script src="{% static 'dist/js/adminlte.js'?????"></script><!-- AdminLTE dashboard demo (This is only for demo purposes) --><script src="{% static 'dist/js/pages/dashboard.js'?????"></script><!-- AdminLTE for demo purposes --><script src="{% static 'dist/js/demo.js'?????"></script></body></html> |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
{% load static %}??????<!DOCTYPE html><html><head>????????????<m"utf-8">????????????<meta htt"X-UA-Compatible" content="IE=edge">????????????<title>College Management System | Dashboard</title>????????????<!-- Tell the browser to be responsive to screen width --"viewport" content="width=device-width, initial-scale=1">????????????<me"viewport" content="width=device-width, initial-scale=1">????????????<!-- Font Awesome -->??????"stylesheet" href="{% static "fontawesome-free/css/all.min.css" %}">????????????<!-- Ionicons -->??????????????????????????????????????????<"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">????????????????"stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">????????????<!-- Tempusdominus Bbootstrap 4 -->??????"stylesheet" href="{% static 'tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css' %}">????????????<!-- iCheck -->??????"stylesheet" href="{% static "icheck-bootstrap/icheck-bootstrap.min.css" %}">????????????<!-- JQVMap -->??????"stylesheet" href="{% static "jqvmap/jqvmap.min.css" %}">????????????<!-- Theme style -->??????"stylesheet" href="{% static 'dist/css/adminlte.min.css'?????">????????????<!-- overlayScrollbars -->??????"stylesheet" href="{% static "overlayScrollbars/css/OverlayScrollbars.min.css" %}">????????????<!-- Daterange picker -->??????"stylesheet" href="{% static "daterangepicker/daterangepicker.css" %}">????????????<!-- summernote -->??????"stylesheet" href="{% static "summernote/summernote-bs4.css" %}">????????????<!-- Google Font: Source Sans Pro -->???????"https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">??????</head>??????????????????{% block content %}????????????{% endblock content %}??????<!-- jQuery -->????????????????????????<!-- Optional JavaScript -->????????????????????????<!-- jQuery firs"https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>????????????????????"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>????????????????????"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>??????<script "{% static "jquery/jquery.min.js"?? %}"></script><!-- jQuery UI 1.11.4 --><script src="{% static "jquery-ui/jquery-ui.min.js"?? %}"></script><!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --><script>????????????$.widget.bridge('uibutton', $.ui.button)</script><!-- Bootstrap 4 --><scr"{% static "bootstrap/js/bootstrap.bundle.min.js"?? %}"></script><!-- ChartJS --><script src="{% static "chart.js/Chart.min.js"?? %}"></script><!-- Sparkline --><script src="{% static "sparklines/sparkline.js"?? %}"></script><!-- JQVMap --><script src="{% static "jqvmap/jquery.vmap.min.js"?? %}"></script><script src="{% static "jqvmap/maps/jquery.vmap.usa.js"?? %}"></script><!-- jQuery Knob Chart --><script src="{% static "jquery-knob/jquery.knob.min.js"?? %}"></script><!-- daterangepicker --><script src="{% static "moment/moment.min.js"?? %}"></script><script src="{% static "daterangepicker/daterangepicker.js"?? %}"></script><!-- Tempusdominus Bootstrap 4 --><script src="{% static "tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"?? %}"></script><!-- Summernote --><script src="{% static "summernote/summernote-bs4.min.js"?? %}"></script><!-- overlayScrollbars --><script src="{% static "overlayScrollbars/js/jquery.overlayScrollbars.min.js"?? %}"></script><!-- AdminLTE App --><script src="{% static 'dist/js/adminlte.js'?????"></script><!-- AdminLTE dashboard demo (This is only for demo purposes) --><script src="{% static 'dist/js/pages/dashboard.js'?????"></script><!-- AdminLTE for demo purposes --><script src="{% static 'dist/js/demo.js'?????"></script></body></html>
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | {% extends 'base.html' %}{% load static %}{% block title %}Home{% endblock title %}??????{% block content %}<html><head>??????<style>img {????????????background-size: cover;}body {background-color: coral;}??????"stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">????????????<scr"https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>????????????<scr"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>????????????<l"stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script><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://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>??????</head>??????<na"navbar navbar-expand-lg navbar-dark bg-dark">?????????????????"navbar-brand" href=""><h3>WELCOME TO CMS</h3></a>????????????<butto"navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">????????????????????"navbar-toggler-icon"></span>????????????</button>?????????"collapse navbar-collapse" id="navbarSupportedContent">??????????????????"navbar-nav mr-auto">????????????????????????</ul>????"form-inline my-2 my-lg-0">?????????????????????????????"form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">-->????????????"/logi" class="btn btn-outline-success my-1 mx-2">Login</a>?????????????????????????????????"form-control mr-sm-2" type="Register" placeholder="Register" aria-label="Register">-->??????????????????"/registration" class="btn btn-outline-success my-1 mx-2">Register</a>????????????????????????"/contact" class="btn btn-outline-danger my-1 mx-2">Contact Us</a>????????????????????????</form>??????????"carouselExampleIndicators" class="carousel slide" data-ride="carousel">????????????<o"carousel-indicators">??????????????????</ol>???"carousel-inner">???????????????????"carousel-item active">????????????????????????????????????{"d-block w-100" src="https://images.unsplash.com/20/cambridge.JPG?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1030&q=80" alt="First slide"> {% endcomment %}?????????????????????"{% static 'dist/img/111.png' %}" class="d-block w-100 h-100 size-cover" alt="...">????????????????????????</div>???????????????"carousel-item">????????????????????????????????????{"d-block w-100" src="https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" alt="Second slide"> {% endcomment %}?????????????????????"{% static 'dist/img/re.png' %}" class="d-block w-100 h-100 size-cover " alt="...">????????????????????????</div>???????????????"carousel-item">????????????????????????????????????{"d-block w-100" src="https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" alt="Second slide"> {% endcomment %}?????????????????????"{% static 'dist/img/e.png' %}" class="d-block w-100 h-100 size-cover " alt="...">????????????????????????</div>???"carousel-item">????????????????????????????????????{"d-block w-100" src="https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" alt="Second slide"> {% endcomment %}?????????????????????"{% static 'dist/img/22.png' %}" class="d-block w-100 h-100 size-cover " alt="...">????????????????????????</div>???"carousel-item">????????????????????????????????????{"d-block w-100" src="https://images.unsplash.com/photo-1503676260728-1c00da094a0b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1009&q=80" alt="Third slide"> {% endcomment %}?????????????????????"{% static 'dist/img/33.png' %}" class="d-block w-100 h-100 size-cover" alt="...">????????????????????????</div>???????"carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">????????????????????"carousel-control-prev-icon" aria-hidden="true"></span>????????????????????"sr-only">Previous</span>????????????</a>?????"carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">????????????????????"carousel-control-next-icon" aria-hidden="true"></span>????????????????????"sr-only">Next</span>????????????</a></div>??????</html>??????{% end |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
{% extends 'base.html' %}{% load static %}{% block title %}Home{% endblock title %}??????{% block content %}<html><head>??????<style>img {????????????background-size: cover;}body {background-color: coral;}??????"stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">????????????<scr"https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>????????????<scr"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>????????????<l"stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script><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://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>??????</head>??????<na"navbar navbar-expand-lg navbar-dark bg-dark">?????????????????"navbar-brand" href=""><h3>WELCOME TO CMS</h3></a>????????????<butto"navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">????????????????????"navbar-toggler-icon"></span>????????????</button>?????????"collapse navbar-collapse" id="navbarSupportedContent">??????????????????"navbar-nav mr-auto">????????????????????????</ul>????"form-inline my-2 my-lg-0">?????????????????????????????"form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">-->????????????"/logi" class="btn btn-outline-success my-1 mx-2">Login</a>?????????????????????????????????"form-control mr-sm-2" type="Register" placeholder="Register" aria-label="Register">-->??????????????????"/registration" class="btn btn-outline-success my-1 mx-2">Register</a>????????????????????????"/contact" class="btn btn-outline-danger my-1 mx-2">Contact Us</a>????????????????????????</form>??????????"carouselExampleIndicators" class="carousel slide" data-ride="carousel">????????????<o"carousel-indicators">??????????????????</ol>???"carousel-inner">???????????????????"carousel-item active">????????????????????????????????????{"d-block w-100" src="https://images.unsplash.com/20/cambridge.JPG?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1030&q=80" alt="First slide"> {% endcomment %}?????????????????????"{% static 'dist/img/111.png' %}" class="d-block w-100 h-100 size-cover" alt="...">????????????????????????</div>???????????????"carousel-item">????????????????????????????????????{"d-block w-100" src="https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" alt="Second slide"> {% endcomment %}?????????????????????"{% static 'dist/img/re.png' %}" class="d-block w-100 h-100 size-cover " alt="...">????????????????????????</div>???????????????"carousel-item">????????????????????????????????????{"d-block w-100" src="https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" alt="Second slide"> {% endcomment %}?????????????????????"{% static 'dist/img/e.png' %}" class="d-block w-100 h-100 size-cover " alt="...">????????????????????????</div>???"carousel-item">????????????????????????????????????{"d-block w-100" src="https://images.unsplash.com/photo-1541339907198-e08756dedf3f?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80" alt="Second slide"> {% endcomment %}?????????????????????"{% static 'dist/img/22.png' %}" class="d-block w-100 h-100 size-cover " alt="...">????????????????????????</div>???"carousel-item">????????????????????????????????????{"d-block w-100" src="https://images.unsplash.com/photo-1503676260728-1c00da094a0b?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1009&q=80" alt="Third slide"> {% endcomment %}?????????????????????"{% static 'dist/img/33.png' %}" class="d-block w-100 h-100 size-cover" alt="...">????????????????????????</div>???????"carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">????????????????????"carousel-control-prev-icon" aria-hidden="true"></span>????????????????????"sr-only">Previous</span>????????????</a>?????"carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">????????????????????"carousel-control-next-icon" aria-hidden="true"></span>????????????????????"sr-only">Next</span>????????????</a></div>??????</html>??????{% end
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | {% extends 'base.html' %}{% load static %}{% block content %}<head>??????????????????<m"utf-8">?????????????????"viewport" content="width=device-width, initial-scale=1.0">??????????????????<title>Untitled</title>????"stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">????????????????"stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">????????????????"stylesheet" href="assets/css/style.css">??????????????????<style>????????????????????????????????????body{????????????????????????????????????height:1000px;????????????????????????????????????????????????????????????????????????????????????background:#475d62;????????????????????????????????????background-color: cover;????????????????????????????????????font-family: sans-seriff;????????????????????????????????????}????????????????????????????????????.login-dark {????????????????????????????????????max-width:320px;????????????????????????????????????width:90%;????????????????????????????????????background-color: #1e2833;????????????????????????????????????padding:40px;????????????????????????????????????border-radius:4px;????????????????????????????????????transform: translate(-50%,-50%);????????????????????????????????????position: absolute;????????????????????????????????????top: 50%;????????????????????????????????????left: 50%;????????????????????????????????????color:#fff;????????????????????????????????????box-shadow:3px 3px 4px rgba(0,0,0,0.2g:15px 0 20px;????????????????????????????????????font-size:100px;????????????????????????????????????color:#2980ef;????????????????????????????????????}????????????????????????????????????.login-dark form .form-control {????????????????????????????????????background:none;????????????????????????????????????border:none;????????????????????????????????????border-bottom:1px solid #434a52;????????????????????????????????????border-radius:0;????????????????????????????????????box-shadow:none;????????????????????????????????????outline:none;????????????????????????????????????color:inherit;????????????????????????????????????}????????????????????????????????????.login-dark form .btn-primary {????????????????????????????????????background:#214a80;????????????????????????????????????border:none;????????????????????????????????????border-radius:4px;????????????????????????????????????padding:11px;????????????????????????????????????box-shadow:none;????????????????????????????????????margin-top:26px;??????????????????ot:hover, .login-dark form .forgot:active {????????????????????????????????????opacity:1;????????????????????????????????????text-decoration:none;????????????????????????????????????}????????????????????????????????????.login-dark form .btn-pri"navbar navbar-expand-lg navbar-dark bg-dark">???????????????"navbar-brand" href="/ ">????????????????????????????????????<h4>BACK TO HOME</h4>??????"navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">??????????????????"navbar-toggler-icon"></span>??????????????????</button>?????"collapse navbar-collapse" id="navbarSupportedContent">??????????????????????"navbar-nav mr-auto">????????????????????????????????????</ul>"form-inline my-2 my-lg-0">????????????????????????????????????"form-control mr-sm-2" type="login" placeholder="login" aria-label="login">-->???????????????????????????????????"form-control mr-sm-2" type="Register" placeholder="Register" aria-label="Register">-->??????????????????????????"/logi" class="btn btn-outline-success my-1 mx-2">Login Here</a>??????????????????????????"/contact" class="btn btn-outline-danger my-1 mx-2">Contact Us</a>???????????????????????????????????"form-control mr-sm-2" type="register" placeholder="register" aria-label="register">-->????????????????????????????????????</form>?????"login-dark form-inline py-0 mx-4 my-4 pl-4 pr-4"><form action="{% url 'doRegistration' %}" method="get">{% csrf_token %}<h1 class="text-center">Signup</h1><div class="illustration"><i class="icon ion-ios-locked-outline"></i></div><div class="form-group"><input class="form-control mb-2" type="text" name="first_name" placeholder="First Name"></div><div class="form-group"><input class="form-control mb-2" type="text" name="last_name" placeholder="Last Name"></div><div class="form-group"><input class="form-control mb-2" type="email" name="email" placeholder="Email"></div><div class="form-group"><input class="form-control mb-2" type="password" name="password" placeholder="Password"></div><div class="form-group"><input class="form-control mb-2" type="password" name="confirmPassword" placeholder="Confirm Password"></div><div class="form-group"><button class="btn btn-primary btn-block mt-2 ml-2" type="submit">Register</button></div>{% comment %} Display Messages {% endcomment %}{% if messages %}<div class="col-12">??????????????????{% for message in messages %}????????????????"error" %}?????????????????"alert alert-danger alert-dismissible fade show" role="alert" style="margin-top: 10px;">????????????????????????????????????<b>{{ message }}</b>?"button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>??????????????????</div>??????????????????{% endif %}??????????????????{% en"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>{% endblock content %} |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
{% extends 'base.html' %}{% load static %}{% block content %}<head>??????????????????<m"utf-8">?????????????????"viewport" content="width=device-width, initial-scale=1.0">??????????????????<title>Untitled</title>????"stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">????????????????"stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">????????????????"stylesheet" href="assets/css/style.css">??????????????????<style>????????????????????????????????????body{????????????????????????????????????height:1000px;????????????????????????????????????????????????????????????????????????????????????background:#475d62;????????????????????????????????????background-color: cover;????????????????????????????????????font-family: sans-seriff;????????????????????????????????????}????????????????????????????????????.login-dark {????????????????????????????????????max-width:320px;????????????????????????????????????width:90%;????????????????????????????????????background-color: #1e2833;????????????????????????????????????padding:40px;????????????????????????????????????border-radius:4px;????????????????????????????????????transform: translate(-50%,-50%);????????????????????????????????????position: absolute;????????????????????????????????????top: 50%;????????????????????????????????????left: 50%;????????????????????????????????????color:#fff;????????????????????????????????????box-shadow:3px 3px 4px rgba(0,0,0,0.2g:15px 0 20px;????????????????????????????????????font-size:100px;????????????????????????????????????color:#2980ef;????????????????????????????????????}????????????????????????????????????.login-dark form .form-control {????????????????????????????????????background:none;????????????????????????????????????border:none;????????????????????????????????????border-bottom:1px solid #434a52;????????????????????????????????????border-radius:0;????????????????????????????????????box-shadow:none;????????????????????????????????????outline:none;????????????????????????????????????color:inherit;????????????????????????????????????}????????????????????????????????????.login-dark form .btn-primary {????????????????????????????????????background:#214a80;????????????????????????????????????border:none;????????????????????????????????????border-radius:4px;????????????????????????????????????padding:11px;????????????????????????????????????box-shadow:none;????????????????????????????????????margin-top:26px;??????????????????ot:hover, .login-dark form .forgot:active {????????????????????????????????????opacity:1;????????????????????????????????????text-decoration:none;????????????????????????????????????}????????????????????????????????????.login-dark form .btn-pri"navbar navbar-expand-lg navbar-dark bg-dark">???????????????"navbar-brand" href="/ ">????????????????????????????????????<h4>BACK TO HOME</h4>??????"navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">??????????????????"navbar-toggler-icon"></span>??????????????????</button>?????"collapse navbar-collapse" id="navbarSupportedContent">??????????????????????"navbar-nav mr-auto">????????????????????????????????????</ul>"form-inline my-2 my-lg-0">????????????????????????????????????"form-control mr-sm-2" type="login" placeholder="login" aria-label="login">-->???????????????????????????????????"form-control mr-sm-2" type="Register" placeholder="Register" aria-label="Register">-->??????????????????????????"/logi" class="btn btn-outline-success my-1 mx-2">Login Here</a>??????????????????????????"/contact" class="btn btn-outline-danger my-1 mx-2">Contact Us</a>???????????????????????????????????"form-control mr-sm-2" type="register" placeholder="register" aria-label="register">-->????????????????????????????????????</form>?????"login-dark form-inline py-0 mx-4 my-4 pl-4 pr-4"><form action="{% url 'doRegistration' %}" method="get">{% csrf_token %}<h1 class="text-center">Signup</h1><div class="illustration"><i class="icon ion-ios-locked-outline"></i></div><div class="form-group"><input class="form-control mb-2" type="text" name="first_name" placeholder="First Name"></div><div class="form-group"><input class="form-control mb-2" type="text" name="last_name" placeholder="Last Name"></div><div class="form-group"><input class="form-control mb-2" type="email" name="email" placeholder="Email"></div><div class="form-group"><input class="form-control mb-2" type="password" name="password" placeholder="Password"></div><div class="form-group"><input class="form-control mb-2" type="password" name="confirmPassword" placeholder="Confirm Password"></div><div class="form-group"><button class="btn btn-primary btn-block mt-2 ml-2" type="submit">Register</button></div>{% comment %} Display Messages {% endcomment %}{% if messages %}<div class="col-12">??????????????????{% for message in messages %}????????????????"error" %}?????????????????"alert alert-danger alert-dismissible fade show" role="alert" style="margin-top: 10px;">????????????????????????????????????<b>{{ message }}</b>?"button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>??????????????????</div>??????????????????{% endif %}??????????????????{% en"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>{% endblock content %}
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | {% extends 'base.html' %}{% load static %}{% block content %}<head>??????????????????<m"utf-8">?????????????????"viewport" content="width=device-width, initial-scale=1; maximum-scale=1.0; user-scalable=0;">??????????????????<title>Untitled</title>????"stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">????????????????"stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">????????????????"stylesheet" href="assets/css/style.css">??????????????????<style>????????????????????????????????????body{????????????????????????????????????height:1000px;????????????????????????????????????background:#475d62;????????????????????????????????????background-color: cover;????????????????????????????????????font-family: sans-seriff;????????????????????????????????????}????????????????????????????????????.login-dark {????????????????????????????????????max-width:320px;????????????????????????????????????width:90%;????????????????????????????????????background-color: #1e2833;????????????????????????????????????padding:40px;????????????????????????????????????border-radius:4px;????????????????????????????????????transform: translate(-50%,-50%);????????????????????????????????????position: absolute;????????????????????????????????????top: 50%;????????????????????????????????????left: 50%;????????????????????????????????????color:#fff;????????????????????????????????????box-shadow:3px 3px 4px rgba(0,0,0,0.2);????????????????????????????????????}???????????????????font-size:100px;????????????color:#2980ef;????????????}????????????.login-dark form .form-control {????????????background:none;????????????border:none;????????????border-bottom:1px solid #434a52;????????????border-radius:0;????????????box-shadow:none;????????????outline:none;????????????color:inherit;????????????}????????????.login-dark form .btn-primary {????????????background:#214a80;????????????border:none;????????????border-radius:4px;????????????padding:11px;????????????box-shadow:none;????????????margin-top:26px;????????????text-shadow:none;????????????outline:none;????????????}????????????.login-dark form .btn-primary:hover, .login-dark form .btn-primary:active {????????????background:#214a80;????????????outline:none;????????????}????????????.login-dark form .forgot {????????????display:block;????????????text-align:center;????????????font-size:12px;????????????color:#6f7a85;????????????opacity:0.9;????????????text-decoration:none;????????????}????????????.login-dark form .forgot:hover, .login-dark form .forgot:active {????????????????????????????????????opacity:1;????????????????????????????????????text-decoration:none;????????????????????????????????????}????????????????????????????????????.login-dark form .btn-pri"navbar navbar-expand-lg navbar-dark bg-dark">???????????????"navbar-brand" href="/ ">BACK TO HOME</a>??????????????????<b"navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">??????????????????"navbar-toggler-icon"></span>??????????????????</button>?????"collapse navbar-collapse" id="navbarSupportedContent">??????????????????????"navbar-nav mr-auto">????????????????????????????????????</ul>"form-inline my-2 my-lg-0">??????????????????????????"{% url 'contact' %}" class="btn btn-outline-danger my-1 mx-2">Contact Us</a>????????????????????????????????????</form>???????????????????"form-inline my-2 my-lg-0">-->??????????????????</div></nav"login-dark form-inline py-0 mx-4 my-4 pl-4 pr-4">??????????????????<"{% url 'doLogin' %}" method="get">????????????????????????????????????{% csrf_token "text-center">Login</h1>???????????????????????"illustration"><i class="icon ion-ios-locked-outline"></i></div>???????????????????????"form-group"><input class="form-control mb-2" type="email" name="email" placeholder="Email"></div>???????????????????????"form-group"><input class="form-control mb-2" type="password" name="password" placeholder="Password"></div>???????????????????????"form-group"><button class="btn btn-primary btn-block mb-2 ml-2" type="submit">Log In</button></div>????????????????????"/registration" class="forgot">Not Registered Yet? Register Now</a>??????????????????</form></div>{% comment %} Display Messages {% endcomment %}{% if messages %"col-12">??????????????????{% for message in messages %}????????????????"error" %}??????????????????{% comment %}?????"alert alert-danger alert-dismissible fade show" role="alert" style="margin-top: 10px;">????????????????????????????????????<b>{{ message }}</b>?"button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>??????????????????</div>??????????????????{% endcom"alert alert-danger alert-dismissible fade show" role="alert">????????????????????????????????????<strong>Invalid Login Credentials!</strong>?"button" class="close" data-dismiss="alert" aria-label="Close">??????????????????????????????"true">??????</span>????????????????????????????????????</button>??????????????????</div>??????????????????{% end"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>{% endblock content %} |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
{% extends 'base.html' %}{% load static %}{% block content %}<head>??????????????????<m"utf-8">?????????????????"viewport" content="width=device-width, initial-scale=1; maximum-scale=1.0; user-scalable=0;">??????????????????<title>Untitled</title>????"stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">????????????????"stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">????????????????"stylesheet" href="assets/css/style.css">??????????????????<style>????????????????????????????????????body{????????????????????????????????????height:1000px;????????????????????????????????????background:#475d62;????????????????????????????????????background-color: cover;????????????????????????????????????font-family: sans-seriff;????????????????????????????????????}????????????????????????????????????.login-dark {????????????????????????????????????max-width:320px;????????????????????????????????????width:90%;????????????????????????????????????background-color: #1e2833;????????????????????????????????????padding:40px;????????????????????????????????????border-radius:4px;????????????????????????????????????transform: translate(-50%,-50%);????????????????????????????????????position: absolute;????????????????????????????????????top: 50%;????????????????????????????????????left: 50%;????????????????????????????????????color:#fff;????????????????????????????????????box-shadow:3px 3px 4px rgba(0,0,0,0.2);????????????????????????????????????}???????????????????font-size:100px;????????????color:#2980ef;????????????}????????????.login-dark form .form-control {????????????background:none;????????????border:none;????????????border-bottom:1px solid #434a52;????????????border-radius:0;????????????box-shadow:none;????????????outline:none;????????????color:inherit;????????????}????????????.login-dark form .btn-primary {????????????background:#214a80;????????????border:none;????????????border-radius:4px;????????????padding:11px;????????????box-shadow:none;????????????margin-top:26px;????????????text-shadow:none;????????????outline:none;????????????}????????????.login-dark form .btn-primary:hover, .login-dark form .btn-primary:active {????????????background:#214a80;????????????outline:none;????????????}????????????.login-dark form .forgot {????????????display:block;????????????text-align:center;????????????font-size:12px;????????????color:#6f7a85;????????????opacity:0.9;????????????text-decoration:none;????????????}????????????.login-dark form .forgot:hover, .login-dark form .forgot:active {????????????????????????????????????opacity:1;????????????????????????????????????text-decoration:none;????????????????????????????????????}????????????????????????????????????.login-dark form .btn-pri"navbar navbar-expand-lg navbar-dark bg-dark">???????????????"navbar-brand" href="/ ">BACK TO HOME</a>??????????????????<b"navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">??????????????????"navbar-toggler-icon"></span>??????????????????</button>?????"collapse navbar-collapse" id="navbarSupportedContent">??????????????????????"navbar-nav mr-auto">????????????????????????????????????</ul>"form-inline my-2 my-lg-0">??????????????????????????"{% url 'contact' %}" class="btn btn-outline-danger my-1 mx-2">Contact Us</a>????????????????????????????????????</form>???????????????????"form-inline my-2 my-lg-0">-->??????????????????</div></nav"login-dark form-inline py-0 mx-4 my-4 pl-4 pr-4">??????????????????<"{% url 'doLogin' %}" method="get">????????????????????????????????????{% csrf_token "text-center">Login</h1>???????????????????????"illustration"><i class="icon ion-ios-locked-outline"></i></div>???????????????????????"form-group"><input class="form-control mb-2" type="email" name="email" placeholder="Email"></div>???????????????????????"form-group"><input class="form-control mb-2" type="password" name="password" placeholder="Password"></div>???????????????????????"form-group"><button class="btn btn-primary btn-block mb-2 ml-2" type="submit">Log In</button></div>????????????????????"/registration" class="forgot">Not Registered Yet? Register Now</a>??????????????????</form></div>{% comment %} Display Messages {% endcomment %}{% if messages %"col-12">??????????????????{% for message in messages %}????????????????"error" %}??????????????????{% comment %}?????"alert alert-danger alert-dismissible fade show" role="alert" style="margin-top: 10px;">????????????????????????????????????<b>{{ message }}</b>?"button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>??????????????????</div>??????????????????{% endcom"alert alert-danger alert-dismissible fade show" role="alert">????????????????????????????????????<strong>Invalid Login Credentials!</strong>?"button" class="close" data-dismiss="alert" aria-label="Close">??????????????????????????????"true">??????</span>????????????????????????????????????</button>??????????????????</div>??????????????????{% end"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>{% endblock content %}
#Output : django-admin startproject student_management_project
[END] |
College Management System using Django - Python Project | https://www.geeksforgeeks.org/college-management-system-using-django-python-project/ | {% extends 'base.html' %}{% load static %}??????{% block content %}?????????????"navbar navbar-expand-lg navbar-dark bg-dark">????????????????????????????????????????????"/ " class="btn btn-outline-primary my-1 mx-2">Go Back To Home </a>??????????????????????????????????????????????????????"navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">????????????????????????????????????????????????????????"navbar-toggler-icon"></span>????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????</button>?????????"collapse navbar-collapse" id="navbarSupportedContent">??????????????????????????????????????????????????????"navbar-nav mr-auto">?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????"form-inline my-2 my-lg-0">????????????????????????????????????????????????????????????????"form-control mr-sm-2" type="login" placeholder="login" aria-label="login">-->???????????????????????????????????????????????????????????????????????????????"form-control mr-sm-2" type="Register" placeholder="Register" aria-label="Register">-->???????????????????????????????????????????????????????????????????????????"form-control mr-sm-2" type="register" placeholder="register" aria-label="register">-->?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????"form-inline my-2 my-lg-0">???????????????????????????????????????????????????????????????????????????????????????????????????"container-fluid px-0">???????????????????"{% static 'dist/img/contact.jpg' %}" class="d-block w-100 mx-0" alt="..." height=450px width=10px></div><div class="container">??????????????????"text-center my-3 display-2">????????????????????????????????????????????????<b>Contact "/contact" method="post">{% csrf_token %}???????????????????"mb-3 py-2">????????????<la"exampleFormControlInput1" class="form-label"><b>Name</b></label>????????????<inp"name" class="form-control" id="exampleFormControlInput1" name = "name" placeholder="Enter your Name"></div>???????????????????????????"mb-3 py-2">???????????????????????????????????"exampleFormControlInput1" class="form-label"><b>Email id</b></label>????????????<inp"email" class="form-control" id="exampleFormControlInpu2"name = "email" placeholder="Enter your Email"></div>???????????????????????????"mb-3 py-2">???????????????????????????????????"exampleFormControlInput1" class="form-label"><b>Phone number</b></label>????????????<inp"number" class="form-control" id="exampleFormControlInput3"?? name = "phone" placeholder="Enter your Phone number"></div><div class="mb-3 py-2">???????????????????"exampleFormControlTextarea1" class="form-label"><b>How can we help you ??</b></label>????????????<textare"form-control" id="exampleFormControlTextarea1" rows="7" name = "desc"></textarea></div>?????????????????????????"submit" class="btn btn-primary btn-lg ">Submit</button>????????????????????????????????????????????????</form>< |
#Output : django-admin startproject student_management_project | College Management System using Django - Python Project
{% extends 'base.html' %}{% load static %}??????{% block content %}?????????????"navbar navbar-expand-lg navbar-dark bg-dark">????????????????????????????????????????????"/ " class="btn btn-outline-primary my-1 mx-2">Go Back To Home </a>??????????????????????????????????????????????????????"navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">????????????????????????????????????????????????????????"navbar-toggler-icon"></span>????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????</button>?????????"collapse navbar-collapse" id="navbarSupportedContent">??????????????????????????????????????????????????????"navbar-nav mr-auto">?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????"form-inline my-2 my-lg-0">????????????????????????????????????????????????????????????????"form-control mr-sm-2" type="login" placeholder="login" aria-label="login">-->???????????????????????????????????????????????????????????????????????????????"form-control mr-sm-2" type="Register" placeholder="Register" aria-label="Register">-->???????????????????????????????????????????????????????????????????????????"form-control mr-sm-2" type="register" placeholder="register" aria-label="register">-->?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????"form-inline my-2 my-lg-0">???????????????????????????????????????????????????????????????????????????????????????????????????"container-fluid px-0">???????????????????"{% static 'dist/img/contact.jpg' %}" class="d-block w-100 mx-0" alt="..." height=450px width=10px></div><div class="container">??????????????????"text-center my-3 display-2">????????????????????????????????????????????????<b>Contact "/contact" method="post">{% csrf_token %}???????????????????"mb-3 py-2">????????????<la"exampleFormControlInput1" class="form-label"><b>Name</b></label>????????????<inp"name" class="form-control" id="exampleFormControlInput1" name = "name" placeholder="Enter your Name"></div>???????????????????????????"mb-3 py-2">???????????????????????????????????"exampleFormControlInput1" class="form-label"><b>Email id</b></label>????????????<inp"email" class="form-control" id="exampleFormControlInpu2"name = "email" placeholder="Enter your Email"></div>???????????????????????????"mb-3 py-2">???????????????????????????????????"exampleFormControlInput1" class="form-label"><b>Phone number</b></label>????????????<inp"number" class="form-control" id="exampleFormControlInput3"?? name = "phone" placeholder="Enter your Phone number"></div><div class="mb-3 py-2">???????????????????"exampleFormControlTextarea1" class="form-label"><b>How can we help you ??</b></label>????????????<textare"form-control" id="exampleFormControlTextarea1" rows="7" name = "desc"></textarea></div>?????????????????????????"submit" class="btn btn-primary btn-lg ">Submit</button>????????????????????????????????????????????????</form><
#Output : django-admin startproject student_management_project
[END] |
Speak the meaning of the word using Python | https://www.geeksforgeeks.org/speak-the-meaning-of-the-word-using-python/ | import pyttsx3
from PyDictionary import PyDictionary
class Speaking:
def speak(self, audio):
# Having the initial constructor of pyttsx3
# and having the sapi5 in it as a parameter
engine = pyttsx3.init("sapi5")
# Calling the getter and setter of pyttsx3
voices = engine.getProperty("voices")
# Method for the speaking of the assistant
engine.setProperty("voice", voices[0].id)
engine.say(audio)
engine.runAndWait()
class GFG:
def Dictionary(self):
speak = Speaking()
dic = PyDictionary()
speak.speak("Which word do u want to find the meaning sir")
# Taking the string input
query = str(input())
word = dic.meaning(query)
print(len(word))
for state in word:
print(word[state])
speak.speak("the meaning is" + str(word[state]))
if __name__ == "__main__":
GFG()
GFG.Dictionary(self=None) |
#Output : pip install PyDictionary | Speak the meaning of the word using Python
import pyttsx3
from PyDictionary import PyDictionary
class Speaking:
def speak(self, audio):
# Having the initial constructor of pyttsx3
# and having the sapi5 in it as a parameter
engine = pyttsx3.init("sapi5")
# Calling the getter and setter of pyttsx3
voices = engine.getProperty("voices")
# Method for the speaking of the assistant
engine.setProperty("voice", voices[0].id)
engine.say(audio)
engine.runAndWait()
class GFG:
def Dictionary(self):
speak = Speaking()
dic = PyDictionary()
speak.speak("Which word do u want to find the meaning sir")
# Taking the string input
query = str(input())
word = dic.meaning(query)
print(len(word))
for state in word:
print(word[state])
speak.speak("the meaning is" + str(word[state]))
if __name__ == "__main__":
GFG()
GFG.Dictionary(self=None)
#Output : pip install PyDictionary
[END] |
Convert PDF File Text to Audio Speech using Python | https://www.geeksforgeeks.org/convert-pdf-file-text-to-audio-speech-using-python/ | # importing the modules
import PyPDF2
import pyttsx3
# path of the PDF file
path = open("file.pdf", "rb")
# creating a PdfFileReader object
pdfReader = PyPDF2.PdfFileReader(path)
# the page with which you want to start
# this will read the page of 25th page.
from_page = pdfReader.getPage(24)
# extracting the text from the PDF
text = from_page.extractText()
# reading the text
speak = pyttsx3.init()
speak.say(text)
speak.runAndWait() |
#Output : pip install pyttsx3
| Convert PDF File Text to Audio Speech using Python
# importing the modules
import PyPDF2
import pyttsx3
# path of the PDF file
path = open("file.pdf", "rb")
# creating a PdfFileReader object
pdfReader = PyPDF2.PdfFileReader(path)
# the page with which you want to start
# this will read the page of 25th page.
from_page = pdfReader.getPage(24)
# extracting the text from the PDF
text = from_page.extractText()
# reading the text
speak = pyttsx3.init()
speak.say(text)
speak.runAndWait()
#Output : pip install pyttsx3
[END] |
Convert Text to Speech in Python | https://www.geeksforgeeks.org/convert-text-speech-python/ | # Import the required module for text
# to speech conversion
from gtts import gTTS
# This module is imported so that we can
# play the converted audio
import os
# The text that you want to convert to audio
mytext = "Welcome to geeksforgeeks!"
# Language in which you want to convert
language = "en"
# Passing the text and language to the engine,
# here we have marked slow=False. Which tells
# the module that the converted audio should
# have a high speed
myobj = gTTS(text=mytext, lang=language, slow=False)
# Saving the converted audio in a mp3 file named
# welcome
myobj.save("welcome.mp3")
# Playing the converted file
os.system("mpg321 welcome.mp3") |
#Output :
| Convert Text to Speech in Python
# Import the required module for text
# to speech conversion
from gtts import gTTS
# This module is imported so that we can
# play the converted audio
import os
# The text that you want to convert to audio
mytext = "Welcome to geeksforgeeks!"
# Language in which you want to convert
language = "en"
# Passing the text and language to the engine,
# here we have marked slow=False. Which tells
# the module that the converted audio should
# have a high speed
myobj = gTTS(text=mytext, lang=language, slow=False)
# Saving the converted audio in a mp3 file named
# welcome
myobj.save("welcome.mp3")
# Playing the converted file
os.system("mpg321 welcome.mp3")
#Output :
[END] |
Python Text To Speech using pyttsx module | https://www.geeksforgeeks.org/python-text-to-speech-pyttsx-module/ | # importing the pyttsx library
import pyttsx3
# initialisation
engine = pyttsx3.init()
# testing
engine.say("My first code on text-to-speech")
engine.say("Thank you, Geeksforgeeks")
engine.runAndWait() |
#Output : pip install pyttsx3 | Python Text To Speech using pyttsx module
# importing the pyttsx library
import pyttsx3
# initialisation
engine = pyttsx3.init()
# testing
engine.say("My first code on text-to-speech")
engine.say("Thank you, Geeksforgeeks")
engine.runAndWait()
#Output : pip install pyttsx3
[END] |
Python Text To Speech using pyttsx module | https://www.geeksforgeeks.org/python-text-to-speech-pyttsx-module/ | import pyttsx3
def onStart():
print("starting")
def onWord(name, location, length):
print("word", name, location, length)
def onEnd(name, completed):
print("finishing", name, completed)
engine = pyttsx3.init()
engine.connect("started-utterance", onStart)
engine.connect("started-word", onWord)
engine.connect("finished-utterance", onEnd)
sen = "Geeks for geeks is a computer portal for Geeks"
engine.say(sen)
engine.runAndWait() |
#Output : pip install pyttsx3 | Python Text To Speech using pyttsx module
import pyttsx3
def onStart():
print("starting")
def onWord(name, location, length):
print("word", name, location, length)
def onEnd(name, completed):
print("finishing", name, completed)
engine = pyttsx3.init()
engine.connect("started-utterance", onStart)
engine.connect("started-word", onWord)
engine.connect("finished-utterance", onEnd)
sen = "Geeks for geeks is a computer portal for Geeks"
engine.say(sen)
engine.runAndWait()
#Output : pip install pyttsx3
[END] |
Convert Speech to text and text to Speech | https://www.geeksforgeeks.org/python-convert-speech-to-text-and-text-to-speech/ | # Python program to translate
# speech to text and text to speech
import speech_recognition as sr
import pyttsx3
# Initialize the recognizer
r = sr.Recognizer()
# Function to convert text to
# speech
def SpeakText(command):
# Initialize the engine
engine = pyttsx3.init()
engine.say(command)
engine.runAndWait()
# Loop infinitely for user to
# speak
while 1:
# Exception handling to handle
# exceptions at the runtime
try:
# use the microphone as source for input.
with sr.Microphone() as source2:
# wait for a second to let the recognizer
# adjust the energy threshold based on
# the surrounding noise level
r.adjust_for_ambient_noise(source2, duration=0.2)
# listens for the user's input
audio2 = r.listen(source2)
# Using google to recognize audio
MyText = r.recognize_google(audio2)
MyText = MyText.lower()
print("Did you say ", MyText)
SpeakText(MyText)
except sr.RequestError as e:
print("Could not request results; {0}".format(e))
except sr.UnknownValueError:
print("unknown error occurred") |
#Output : pip install speechrecognition | Convert Speech to text and text to Speech
# Python program to translate
# speech to text and text to speech
import speech_recognition as sr
import pyttsx3
# Initialize the recognizer
r = sr.Recognizer()
# Function to convert text to
# speech
def SpeakText(command):
# Initialize the engine
engine = pyttsx3.init()
engine.say(command)
engine.runAndWait()
# Loop infinitely for user to
# speak
while 1:
# Exception handling to handle
# exceptions at the runtime
try:
# use the microphone as source for input.
with sr.Microphone() as source2:
# wait for a second to let the recognizer
# adjust the energy threshold based on
# the surrounding noise level
r.adjust_for_ambient_noise(source2, duration=0.2)
# listens for the user's input
audio2 = r.listen(source2)
# Using google to recognize audio
MyText = r.recognize_google(audio2)
MyText = MyText.lower()
print("Did you say ", MyText)
SpeakText(MyText)
except sr.RequestError as e:
print("Could not request results; {0}".format(e))
except sr.UnknownValueError:
print("unknown error occurred")
#Output : pip install speechrecognition
[END] |
Personal Voice Assistant in Python | https://www.geeksforgeeks.org/personal-voice-assistant-in-python/ | # importing speech recognition package from google api
import speech_recognition as sr
import playsound # to play saved mp3 file
from gtts import gTTS # google text to speech
import os # to save/open files
import wolframalpha # to calculate strings into formula
from selenium import webdriver # to control browser operations
num = 1
def assistant_speaks(output):
global num
# num to rename every audio file
# with different name to remove ambiguity
num += 1
print("PerSon : ", output)
toSpeak = gTTS(text = output, lang ='en', slow = False)
# saving the audio file given by google text to speech
file = str(num)+".mp3
toSpeak.save(file)
# playsound package is used to play the same file.
playsound.playsound(file, True)
os.remove(file)
def get_audio():
rObject = sr.Recognizer()
audio = ''
with sr.Microphone() as source:
print("Speak...")
# recording the audio using speech recognition
audio = rObject.listen(source, phrase_time_limit = 5)
print("Stop.") # limit 5 secs
try:
text = rObject.recognize_google(audio, language ='en-US')
print("You : ", text)
return text
except:
assistant_speaks("Could not understand your audio, PLease try again !")
return 0
# Driver Code
if __name__ == "__main__":
assistant_speaks("What's your name, Human?")
name ='Human'
name = get_audio()
assistant_speaks("Hello, " + name + '.')
while(1):
assistant_speaks("What can i do for you?")
text = get_audio().lower()
if text == 0:
continue
if "exit" in str(text) or "bye" in str(text) or "sleep" in str(text):
assistant_speaks("Ok bye, "+ name+'.')
break
# calling process text to process the query
process_text(text) |
#Output : 1. Say "Search google Geeks for Geeks" | Personal Voice Assistant in Python
# importing speech recognition package from google api
import speech_recognition as sr
import playsound # to play saved mp3 file
from gtts import gTTS # google text to speech
import os # to save/open files
import wolframalpha # to calculate strings into formula
from selenium import webdriver # to control browser operations
num = 1
def assistant_speaks(output):
global num
# num to rename every audio file
# with different name to remove ambiguity
num += 1
print("PerSon : ", output)
toSpeak = gTTS(text = output, lang ='en', slow = False)
# saving the audio file given by google text to speech
file = str(num)+".mp3
toSpeak.save(file)
# playsound package is used to play the same file.
playsound.playsound(file, True)
os.remove(file)
def get_audio():
rObject = sr.Recognizer()
audio = ''
with sr.Microphone() as source:
print("Speak...")
# recording the audio using speech recognition
audio = rObject.listen(source, phrase_time_limit = 5)
print("Stop.") # limit 5 secs
try:
text = rObject.recognize_google(audio, language ='en-US')
print("You : ", text)
return text
except:
assistant_speaks("Could not understand your audio, PLease try again !")
return 0
# Driver Code
if __name__ == "__main__":
assistant_speaks("What's your name, Human?")
name ='Human'
name = get_audio()
assistant_speaks("Hello, " + name + '.')
while(1):
assistant_speaks("What can i do for you?")
text = get_audio().lower()
if text == 0:
continue
if "exit" in str(text) or "bye" in str(text) or "sleep" in str(text):
assistant_speaks("Ok bye, "+ name+'.')
break
# calling process text to process the query
process_text(text)
#Output : 1. Say "Search google Geeks for Geeks"
[END] |
Personal Voice Assistant in Python | https://www.geeksforgeeks.org/personal-voice-assistant-in-python/ | def process_text(input):
try:
if "search" in input or "play" in input:
# a basic web crawler using selenium
search_web(input)
return
elif "who are you" in input or "define yourself" in input:
speak = """Hello, I am Person. Your personal Assistant.
I am here to make your life easier. You can command me to perform
various tasks such as calculating sums or opening applications etcetra"""
assistant_speaks(speak)
return
elif "who made you" in input or "created you" in input:
speak = "I have been created by Sheetansh Kumar."
assistant_speaks(speak)
return
elif "geeksforgeeks" in input: # just
speak = (
"""Geeks for Geeks is the Best Online Coding Platform for learning."""
)
assistant_speaks(speak)
return
elif "calculate" in input.lower():
# write your wolframalpha app_id here
app_id = "WOLFRAMALPHA_APP_ID"
client = wolframalpha.Client(app_id)
indx = input.lower().split().index("calculate")
query = input.split()[indx + 1 :]
res = client.query(" ".join(query))
answer = next(res.results).text
assistant_speaks("The answer is " + answer)
return
elif "open" in input:
# another function to open
# different application available
open_application(input.lower())
return
else:
assistant_speaks("I can search the web for you, Do you want to continue?")
ans = get_audio()
if "yes" in str(ans) or "yeah" in str(ans):
search_web(input)
else:
return
except:
assistant_speaks(
"I don't understand, I can search the web for you, Do you want to continue?"
)
ans = get_audio()
if "yes" in str(ans) or "yeah" in str(ans):
search_web(input) |
#Output : 1. Say "Search google Geeks for Geeks" | Personal Voice Assistant in Python
def process_text(input):
try:
if "search" in input or "play" in input:
# a basic web crawler using selenium
search_web(input)
return
elif "who are you" in input or "define yourself" in input:
speak = """Hello, I am Person. Your personal Assistant.
I am here to make your life easier. You can command me to perform
various tasks such as calculating sums or opening applications etcetra"""
assistant_speaks(speak)
return
elif "who made you" in input or "created you" in input:
speak = "I have been created by Sheetansh Kumar."
assistant_speaks(speak)
return
elif "geeksforgeeks" in input: # just
speak = (
"""Geeks for Geeks is the Best Online Coding Platform for learning."""
)
assistant_speaks(speak)
return
elif "calculate" in input.lower():
# write your wolframalpha app_id here
app_id = "WOLFRAMALPHA_APP_ID"
client = wolframalpha.Client(app_id)
indx = input.lower().split().index("calculate")
query = input.split()[indx + 1 :]
res = client.query(" ".join(query))
answer = next(res.results).text
assistant_speaks("The answer is " + answer)
return
elif "open" in input:
# another function to open
# different application available
open_application(input.lower())
return
else:
assistant_speaks("I can search the web for you, Do you want to continue?")
ans = get_audio()
if "yes" in str(ans) or "yeah" in str(ans):
search_web(input)
else:
return
except:
assistant_speaks(
"I don't understand, I can search the web for you, Do you want to continue?"
)
ans = get_audio()
if "yes" in str(ans) or "yeah" in str(ans):
search_web(input)
#Output : 1. Say "Search google Geeks for Geeks"
[END] |
Personal Voice Assistant in Python | https://www.geeksforgeeks.org/personal-voice-assistant-in-python/ | def search_web(input):
driver = webdriver.Firefox()
driver.implicitly_wait(1)
driver.maximize_window()
if "youtube" in input.lower():
assistant_speaks("Opening in youtube")
indx = input.lower().split().index("youtube")
query = input.split()[indx + 1 :]
driver.get("http://www.youtube.com/results?search_query =" + "+".join(query))
return
elif "wikipedia" in input.lower():
assistant_speaks("Opening Wikipedia")
indx = input.lower().split().index("wikipedia")
query = input.split()[indx + 1 :]
driver.get("https://en.wikipedia.org/wiki/" + "_".join(query))
return
else:
if "google" in input:
indx = input.lower().split().index("google")
query = input.split()[indx + 1 :]
driver.get("https://www.google.com/search?q =" + "+".join(query))
elif "search" in input:
indx = input.lower().split().index("google")
query = input.split()[indx + 1 :]
driver.get("https://www.google.com/search?q =" + "+".join(query))
else:
driver.get("https://www.google.com/search?q =" + "+".join(input.split()))
return
# function used to open application
# present inside the system.
def open_application(input):
if "chrome" in input:
assistant_speaks("Google Chrome")
os.startfile("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
return
elif "firefox" in input or "mozilla" in input:
assistant_speaks("Opening Mozilla Firefox")
os.startfile("C:\Program Files\Mozilla Firefox\\firefox.exe")
return
elif "word" in input:
assistant_speaks("Opening Microsoft Word")
os.startfile(
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office 2013\\Word 2013.lnk"
)
return
elif "excel" in input:
assistant_speaks("Opening Microsoft Excel")
os.startfile(
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office 2013\\Excel 2013.lnk"
)
return
else:
assistant_speaks("Application not available")
return |
#Output : 1. Say "Search google Geeks for Geeks" | Personal Voice Assistant in Python
def search_web(input):
driver = webdriver.Firefox()
driver.implicitly_wait(1)
driver.maximize_window()
if "youtube" in input.lower():
assistant_speaks("Opening in youtube")
indx = input.lower().split().index("youtube")
query = input.split()[indx + 1 :]
driver.get("http://www.youtube.com/results?search_query =" + "+".join(query))
return
elif "wikipedia" in input.lower():
assistant_speaks("Opening Wikipedia")
indx = input.lower().split().index("wikipedia")
query = input.split()[indx + 1 :]
driver.get("https://en.wikipedia.org/wiki/" + "_".join(query))
return
else:
if "google" in input:
indx = input.lower().split().index("google")
query = input.split()[indx + 1 :]
driver.get("https://www.google.com/search?q =" + "+".join(query))
elif "search" in input:
indx = input.lower().split().index("google")
query = input.split()[indx + 1 :]
driver.get("https://www.google.com/search?q =" + "+".join(query))
else:
driver.get("https://www.google.com/search?q =" + "+".join(input.split()))
return
# function used to open application
# present inside the system.
def open_application(input):
if "chrome" in input:
assistant_speaks("Google Chrome")
os.startfile("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
return
elif "firefox" in input or "mozilla" in input:
assistant_speaks("Opening Mozilla Firefox")
os.startfile("C:\Program Files\Mozilla Firefox\\firefox.exe")
return
elif "word" in input:
assistant_speaks("Opening Microsoft Word")
os.startfile(
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office 2013\\Word 2013.lnk"
)
return
elif "excel" in input:
assistant_speaks("Opening Microsoft Excel")
os.startfile(
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office 2013\\Excel 2013.lnk"
)
return
else:
assistant_speaks("Application not available")
return
#Output : 1. Say "Search google Geeks for Geeks"
[END] |
Build a Virtual Assistant Using Python | https://www.geeksforgeeks.org/build-a-virtual-assistant-using-python/ | def speak(audio):
engine = pyttsx3.init()
# getter method(gets the current value
# of engine property)
voices = engine.getProperty("voices")
# setter method .[0]=male voice and
# [1]=female voice in set Property.
engine.setProperty("voice", voices[0].id)
# Method for the speaking of the assistant
engine.say(audio)
# Blocks while processing all the currently
# queued commands
engine.runAndWait() |
#Output : pip install pyttsx3 | Build a Virtual Assistant Using Python
def speak(audio):
engine = pyttsx3.init()
# getter method(gets the current value
# of engine property)
voices = engine.getProperty("voices")
# setter method .[0]=male voice and
# [1]=female voice in set Property.
engine.setProperty("voice", voices[0].id)
# Method for the speaking of the assistant
engine.say(audio)
# Blocks while processing all the currently
# queued commands
engine.runAndWait()
#Output : pip install pyttsx3
[END] |
Build a Virtual Assistant Using Python | https://www.geeksforgeeks.org/build-a-virtual-assistant-using-python/ | def Take_query():
# calling the Hello function for
# making it more interactive
Hello()
# This loop is infinite as it will take
# our queries continuously until and unless
# we do not say bye to exit or terminate
# the program
while True:
# taking the query and making it into
# lower case so that most of the times
# query matches and we get the perfect
# output
query = takeCommand().lower()
if "open geeksforgeeks" in query:
speak("Opening GeeksforGeeks ")
# in the open method we just to give the link
# of the website and it automatically open
# it in your default browser
webbrowser.open("www.geeksforgeeks.com")
continue
elif "open google" in query:
speak("Opening Google ")
webbrowser.open("www.google.com")
continue
elif "which day it is" in query:
tellDay()
continue
elif "tell me the time" in query:
tellTime()
continue
# this will exit and terminate the program
elif "bye" in query:
speak("Bye. Check Out GFG for more exciting things")
exit()
elif "from wikipedia" in query:
# if any one wants to have a information
# from wikipedia
speak("Checking the wikipedia ")
query = query.replace("wikipedia", "")
# it will give the summary of 4 lines from
# wikipedia we can increase and decrease
# it also.
result = wikipedia.summary(query, sentences=4)
speak("According to wikipedia")
speak(result)
elif "tell me your name" in query:
speak("I am Jarvis. Your desktop Assistant") |
#Output : pip install pyttsx3 | Build a Virtual Assistant Using Python
def Take_query():
# calling the Hello function for
# making it more interactive
Hello()
# This loop is infinite as it will take
# our queries continuously until and unless
# we do not say bye to exit or terminate
# the program
while True:
# taking the query and making it into
# lower case so that most of the times
# query matches and we get the perfect
# output
query = takeCommand().lower()
if "open geeksforgeeks" in query:
speak("Opening GeeksforGeeks ")
# in the open method we just to give the link
# of the website and it automatically open
# it in your default browser
webbrowser.open("www.geeksforgeeks.com")
continue
elif "open google" in query:
speak("Opening Google ")
webbrowser.open("www.google.com")
continue
elif "which day it is" in query:
tellDay()
continue
elif "tell me the time" in query:
tellTime()
continue
# this will exit and terminate the program
elif "bye" in query:
speak("Bye. Check Out GFG for more exciting things")
exit()
elif "from wikipedia" in query:
# if any one wants to have a information
# from wikipedia
speak("Checking the wikipedia ")
query = query.replace("wikipedia", "")
# it will give the summary of 4 lines from
# wikipedia we can increase and decrease
# it also.
result = wikipedia.summary(query, sentences=4)
speak("According to wikipedia")
speak(result)
elif "tell me your name" in query:
speak("I am Jarvis. Your desktop Assistant")
#Output : pip install pyttsx3
[END] |
Build a Virtual Assistant Using Python | https://www.geeksforgeeks.org/build-a-virtual-assistant-using-python/ | # this method is for taking the commands
# and recognizing the command from the
# speech_Recognition module we will use
# the recongizer method for recognizing
def takeCommand():
r = sr.Recognizer()
# from the speech_Recognition module
# we will use the Microphone module
# for listening the command
with sr.Microphone() as source:
print("Listening")
# seconds of non-speaking audio before
# a phrase is considered complete
r.pause_threshold = 0.7
audio = r.listen(source)
# Now we will be using the try and catch
# method so that if sound is recognized
# it is good else we will have exception
# handling
try:
print("Recognizing")
# for Listening the command in indian
# english we can also use 'hi-In'
# for hindi recognizing
Query = r.recognize_google(audio, language="en-in")
print("the command is printed=", Query)
except Exception as e:
print(e)
print("Say that again sir")
return "None"
return Query |
#Output : pip install pyttsx3 | Build a Virtual Assistant Using Python
# this method is for taking the commands
# and recognizing the command from the
# speech_Recognition module we will use
# the recongizer method for recognizing
def takeCommand():
r = sr.Recognizer()
# from the speech_Recognition module
# we will use the Microphone module
# for listening the command
with sr.Microphone() as source:
print("Listening")
# seconds of non-speaking audio before
# a phrase is considered complete
r.pause_threshold = 0.7
audio = r.listen(source)
# Now we will be using the try and catch
# method so that if sound is recognized
# it is good else we will have exception
# handling
try:
print("Recognizing")
# for Listening the command in indian
# english we can also use 'hi-In'
# for hindi recognizing
Query = r.recognize_google(audio, language="en-in")
print("the command is printed=", Query)
except Exception as e:
print(e)
print("Say that again sir")
return "None"
return Query
#Output : pip install pyttsx3
[END] |
Build a Virtual Assistant Using Python | https://www.geeksforgeeks.org/build-a-virtual-assistant-using-python/ | # code
def tellTime(self):
# This method will give the time
time = str(datetime.datetime.now())
# the time will be displayed like this "2020-06-05 17:50:14.582630"
# nd then after slicing we can get time
print(time)
hour = time[11:13]
min = time[14:16]
self.Speak(self, "The time is sir" + hour + "Hours and" + min + "Minutes")
"""
This method will take time and slice it "2020-06-05 17:50:14.582630" from 11 to 12 for hour
and 14-15 for min and then speak function will be called and then it will speak the current
time
""" |
#Output : pip install pyttsx3 | Build a Virtual Assistant Using Python
# code
def tellTime(self):
# This method will give the time
time = str(datetime.datetime.now())
# the time will be displayed like this "2020-06-05 17:50:14.582630"
# nd then after slicing we can get time
print(time)
hour = time[11:13]
min = time[14:16]
self.Speak(self, "The time is sir" + hour + "Hours and" + min + "Minutes")
"""
This method will take time and slice it "2020-06-05 17:50:14.582630" from 11 to 12 for hour
and 14-15 for min and then speak function will be called and then it will speak the current
time
"""
#Output : pip install pyttsx3
[END] |
Build a Virtual Assistant Using Python | https://www.geeksforgeeks.org/build-a-virtual-assistant-using-python/ | def Hello():????????????????????????# This function is for when the assistant????????????????????????# is called it will say hello and then??"hello sir I am your desktop assistant. /??????????????????????????????????????????????") |
#Output : pip install pyttsx3 | Build a Virtual Assistant Using Python
def Hello():????????????????????????# This function is for when the assistant????????????????????????# is called it will say hello and then??"hello sir I am your desktop assistant. /??????????????????????????????????????????????")
#Output : pip install pyttsx3
[END] |
Build a Virtual Assistant Using Python | https://www.geeksforgeeks.org/build-a-virtual-assistant-using-python/ | if __name__ == "__main__":
# main method for executing
# the functions
Take_query() |
#Output : pip install pyttsx3 | Build a Virtual Assistant Using Python
if __name__ == "__main__":
# main method for executing
# the functions
Take_query()
#Output : pip install pyttsx3
[END] |
Build a Virtual Assistant Using Python | https://www.geeksforgeeks.org/build-a-virtual-assistant-using-python/ | import pyttsx3import speech_recognition as srimport webbrowser??????import datetime??????import wikipedia????????????# this method is for taking the commands# and recognizing the command from the# speech_Recognition module we will use# the recongizer method for recognizingdef takeCommand():??????????????????????????????r = sr.Recognizer()??????????????????????????????# from the speech_Recognition module????????????????????????# we will use the Microphone module????????????????????????# for listening the command????????????????????????with sr.Microphone() as source:????????????????????????????????????????????????print('Listening')??????????????????????????????????????????????????????????????????????????????????????????????????????# seconds of non-speaking audio before????????????????????????????????????????????????# a phrase is considered complete????????????????????????????????????????????????r.pause_threshold = 0.7?????????????????????????????????"Recognizing")??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# for Listening the command in indian????????????????????????????????????????????????????????????????????????# english we can also use 'hi-In'????"the command is printed=", Query)??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????"Say that again sir")???????????????????????????????"None"??????????????????????????????????return Query??def speak(audio):??????????????????engine = pyttsx3.init()????????# getter method(gets the current value????????# of engine property)????????voices = engine.getProperty('voices')??????????????????# setter method .[0]=male voice and????????# [1]=female voice in set Property.????????engine.setProperty('voice', voices[0].id)??????????????????# Method for the speaking of the assistant????????engine.say(audio)????????????????????# Blocks while processing all the currently????????# queued commands????????engine.runAndWait()??def tellDay():??????????????????# This function is for telling the????????# day of the week????????day = datetime.datetime.today().weekday() + 1??????????????????#this line tells us about the number????????# that will help us in telling the day????????Day_dict = {1: 'Monday', 2: 'Tuesday',????????????????????????????????3: 'Wednesday', 4: 'Thursday',????????????????????????????????5: 'Friday', 6: 'Saturday',????????????????????????????????7: 'Sunday'}??????????????????????????????????????????????????????if day in Day_dict.keys():????????????????????????????????????????????????day_of_the_week = Day_d"The day is " + day_of_the_week)????????????def tellTime():??????????????????????????????????????????????????????# This method will give the time????????????????????????time = str(datetime.datetime.now())??????"2020-06-05 17:50:14.582630"????????#nd then after slicing we can get time????????print(time)????????hour = time[11:13]????????min = time[14:16]????????speak(self, "The time is sir" + hour + "Hours and" + min + "Minutes")????????????????????????def Hello():??????????????????????????????????????????????????????# This function is for when the assistant????????????????????????# is"hello sir I am your desktop assistant. /??????????????????????????????????????????????")????????????def Take_query():??????????????????????????????# calling the Hello function for????????????????????????# making it more interactive????????????????????????Hello()??????????????????????????????????????????????????????# This loop is infinite as it will take????????????????????????# our queries continuously until and unless????????????????????????# we do not say bye to exit or terminate????????????????????????# the program????????????????????????while(True):??????????????????????????????????????????????????????????????????????????????????????????????????????# tak"open geeksforgeeks" in query:??????????????????????????????"Opening GeeksforGeeks ")??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# in the open method we just to give the link??????????????????????????????????????????????????????????"www.geeksforgeeks.com")???????????????????????????????????????????????????????????????????????"open google" in query:??????????????????????????????"Opening Google ")????????????????????????????????????????"www.google.com")????????????????????????????????????????????????????????????????????????continu"which day it is" in query:????????????????????????????????????????????????????????????????????????tellDay()???????????????????????"tell me the time" in query:????????????????????????????????????????????????????????????????????????tellTime()????????????????????????????????????????????????????????????????????????continue?"bye" in query:??????????????????????????????"Bye. Check Out GFG for more exciting things")?????????????????????????????????????????????????????????????????????"from wikipedia" in query:??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# if any o"Checking the wikipedia ")??????????????????????????????????????????????"wikipedia", "")??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# it will give the summary of 4 lines from????????????????????????????????????????????????????????????????????????# wikipedia we can increas"According to wikipedia")????????????????????????????????????????????????????????????????????????spea"tell me your name" in query:??????????????????????????????"I am Jarvis. Your desktop Assistant")??????if __name__ == '__main__':??????????????????????????????????????????????????????# main method for executing??? |
#Output : pip install pyttsx3 | Build a Virtual Assistant Using Python
import pyttsx3import speech_recognition as srimport webbrowser??????import datetime??????import wikipedia????????????# this method is for taking the commands# and recognizing the command from the# speech_Recognition module we will use# the recongizer method for recognizingdef takeCommand():??????????????????????????????r = sr.Recognizer()??????????????????????????????# from the speech_Recognition module????????????????????????# we will use the Microphone module????????????????????????# for listening the command????????????????????????with sr.Microphone() as source:????????????????????????????????????????????????print('Listening')??????????????????????????????????????????????????????????????????????????????????????????????????????# seconds of non-speaking audio before????????????????????????????????????????????????# a phrase is considered complete????????????????????????????????????????????????r.pause_threshold = 0.7?????????????????????????????????"Recognizing")??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# for Listening the command in indian????????????????????????????????????????????????????????????????????????# english we can also use 'hi-In'????"the command is printed=", Query)??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????"Say that again sir")???????????????????????????????"None"??????????????????????????????????return Query??def speak(audio):??????????????????engine = pyttsx3.init()????????# getter method(gets the current value????????# of engine property)????????voices = engine.getProperty('voices')??????????????????# setter method .[0]=male voice and????????# [1]=female voice in set Property.????????engine.setProperty('voice', voices[0].id)??????????????????# Method for the speaking of the assistant????????engine.say(audio)????????????????????# Blocks while processing all the currently????????# queued commands????????engine.runAndWait()??def tellDay():??????????????????# This function is for telling the????????# day of the week????????day = datetime.datetime.today().weekday() + 1??????????????????#this line tells us about the number????????# that will help us in telling the day????????Day_dict = {1: 'Monday', 2: 'Tuesday',????????????????????????????????3: 'Wednesday', 4: 'Thursday',????????????????????????????????5: 'Friday', 6: 'Saturday',????????????????????????????????7: 'Sunday'}??????????????????????????????????????????????????????if day in Day_dict.keys():????????????????????????????????????????????????day_of_the_week = Day_d"The day is " + day_of_the_week)????????????def tellTime():??????????????????????????????????????????????????????# This method will give the time????????????????????????time = str(datetime.datetime.now())??????"2020-06-05 17:50:14.582630"????????#nd then after slicing we can get time????????print(time)????????hour = time[11:13]????????min = time[14:16]????????speak(self, "The time is sir" + hour + "Hours and" + min + "Minutes")????????????????????????def Hello():??????????????????????????????????????????????????????# This function is for when the assistant????????????????????????# is"hello sir I am your desktop assistant. /??????????????????????????????????????????????")????????????def Take_query():??????????????????????????????# calling the Hello function for????????????????????????# making it more interactive????????????????????????Hello()??????????????????????????????????????????????????????# This loop is infinite as it will take????????????????????????# our queries continuously until and unless????????????????????????# we do not say bye to exit or terminate????????????????????????# the program????????????????????????while(True):??????????????????????????????????????????????????????????????????????????????????????????????????????# tak"open geeksforgeeks" in query:??????????????????????????????"Opening GeeksforGeeks ")??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# in the open method we just to give the link??????????????????????????????????????????????????????????"www.geeksforgeeks.com")???????????????????????????????????????????????????????????????????????"open google" in query:??????????????????????????????"Opening Google ")????????????????????????????????????????"www.google.com")????????????????????????????????????????????????????????????????????????continu"which day it is" in query:????????????????????????????????????????????????????????????????????????tellDay()???????????????????????"tell me the time" in query:????????????????????????????????????????????????????????????????????????tellTime()????????????????????????????????????????????????????????????????????????continue?"bye" in query:??????????????????????????????"Bye. Check Out GFG for more exciting things")?????????????????????????????????????????????????????????????????????"from wikipedia" in query:??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# if any o"Checking the wikipedia ")??????????????????????????????????????????????"wikipedia", "")??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# it will give the summary of 4 lines from????????????????????????????????????????????????????????????????????????# wikipedia we can increas"According to wikipedia")????????????????????????????????????????????????????????????????????????spea"tell me your name" in query:??????????????????????????????"I am Jarvis. Your desktop Assistant")??????if __name__ == '__main__':??????????????????????????????????????????????????????# main method for executing???
#Output : pip install pyttsx3
[END] |
Create a simple assistant using Wolfram Alpha API | https://www.geeksforgeeks.org/python-create-a-simple-assistant-using-wolfram-alpha-api/ | # Python program to??????# demonstrate creation of an# assistant using wolf ram API????????????import wolframalpha????????????# Taking input from userquestion = input('Question: ')????????????# App id obtained by the above stepsapp_id = ?????????Your app_id?????????????????????# Instance of wolf ram alpha??????# client classclient = wolframalpha.Client(app_id)????????????# Stores the response from??????# wolf ram alphares = client.query(question)????????????# Includes onl | #Input : What is the capital of India?
| Create a simple assistant using Wolfram Alpha API
# Python program to??????# demonstrate creation of an# assistant using wolf ram API????????????import wolframalpha????????????# Taking input from userquestion = input('Question: ')????????????# App id obtained by the above stepsapp_id = ?????????Your app_id?????????????????????# Instance of wolf ram alpha??????# client classclient = wolframalpha.Client(app_id)????????????# Stores the response from??????# wolf ram alphares = client.query(question)????????????# Includes onl
#Input : What is the capital of India?
[END] |
Voice Assistant using python | https://www.geeksforgeeks.org/voice-assistant-using-python/ | import subprocess
import wolframalpha
import pyttsx3
import tkinter
import json
import random
import operator
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import winshell
import pyjokes
import feedparser
import smtplib
import ctypes
import time
import requests
import shutil
from twilio.rest import Client
from clint.textui import progress
from ecapture import ecapture as ec
from bs4 import BeautifulSoup
import win32com.client as wincl
from urllib.request import urlopen |
#Output : pip install wolframalpha | Voice Assistant using python
import subprocess
import wolframalpha
import pyttsx3
import tkinter
import json
import random
import operator
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import winshell
import pyjokes
import feedparser
import smtplib
import ctypes
import time
import requests
import shutil
from twilio.rest import Client
from clint.textui import progress
from ecapture import ecapture as ec
from bs4 import BeautifulSoup
import win32com.client as wincl
from urllib.request import urlopen
#Output : pip install wolframalpha
[END] |
Voice Assistant using python | https://www.geeksforgeeks.org/voice-assistant-using-python/ | engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[1].id) |
#Output : pip install wolframalpha | Voice Assistant using python
engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[1].id)
#Output : pip install wolframalpha
[END] |
Voice Assistant using python | https://www.geeksforgeeks.org/voice-assistant-using-python/ | def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishMe():
hour = int(datetime.datetime.now().hour)
if hour >= 0 and hour < 12:
speak("Good Morning Sir !")
elif hour >= 12 and hour < 18:
speak("Good Afternoon Sir !")
else:
speak("Good Evening Sir !")
assname = "Jarvis 1 point o"
speak("I am your Assistant")
speak(assname)
def username():
speak("What should i call you sir")
uname = takeCommand()
speak("Welcome Mister")
speak(uname)
columns = shutil.get_terminal_size().columns
print("#####################".center(columns))
print("Welcome Mr.", uname.center(columns))
print("#####################".center(columns))
speak("How can i Help you, Sir")
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language="en-in")
print(f"User said: {query}\n")
except Exception as e:
print(e)
print("Unable to Recognize your voice.")
return "None"
return query
def sendEmail(to, content):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
# Enable low security in gmail
server.login("your email id", "your email password")
server.sendmail("your email id", to, content)
server.close() |
#Output : pip install wolframalpha | Voice Assistant using python
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishMe():
hour = int(datetime.datetime.now().hour)
if hour >= 0 and hour < 12:
speak("Good Morning Sir !")
elif hour >= 12 and hour < 18:
speak("Good Afternoon Sir !")
else:
speak("Good Evening Sir !")
assname = "Jarvis 1 point o"
speak("I am your Assistant")
speak(assname)
def username():
speak("What should i call you sir")
uname = takeCommand()
speak("Welcome Mister")
speak(uname)
columns = shutil.get_terminal_size().columns
print("#####################".center(columns))
print("Welcome Mr.", uname.center(columns))
print("#####################".center(columns))
speak("How can i Help you, Sir")
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language="en-in")
print(f"User said: {query}\n")
except Exception as e:
print(e)
print("Unable to Recognize your voice.")
return "None"
return query
def sendEmail(to, content):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
# Enable low security in gmail
server.login("your email id", "your email password")
server.sendmail("your email id", to, content)
server.close()
#Output : pip install wolframalpha
[END] |
Voice Assistant using python | https://www.geeksforgeeks.org/voice-assistant-using-python/ | if __name__ == "__main__":
clear = lambda: os.system("cls")
# This Function will clean any
# command before execution of this python file
clear()
wishMe()
username()
while True:
query = takeCommand().lower()
# All the commands said by user will be
# stored here in 'query' and will be
# converted to lower case for easily
# recognition of command
if "wikipedia" in query:
speak("Searching Wikipedia...")
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=3)
speak("According to Wikipedia")
print(results)
speak(results)
elif "open youtube" in query:
speak("Here you go to Youtube\n")
webbrowser.open("youtube.com")
elif "open google" in query:
speak("Here you go to Google\n")
webbrowser.open("google.com")
elif "open stackoverflow" in query:
speak("Here you go to Stack Over flow.Happy coding")
webbrowser.open("stackoverflow.com")
elif "play music" in query or "play song" in query:
speak("Here you go with music")
# music_dir = "G:\\Song"
music_dir = "C:\\Users\\GAURAV\\Music"
songs = os.listdir(music_dir)
print(songs)
random = os.startfile(os.path.join(music_dir, songs[1]))
elif "the time" in query:
strTime = datetime.datetime.now().strftime("% H:% M:% S")
speak(f"Sir, the time is {strTime}")
elif "open opera" in query:
codePath = (
r"C:\\Users\\GAURAV\\AppData\\Local\\Programs\\Opera\\launcher.exe"
)
os.startfile(codePath)
elif "email to gaurav" in query:
try:
speak("What should I say?")
content = takeCommand()
to = "Receiver email address"
sendEmail(to, content)
speak("Email has been sent !")
except Exception as e:
print(e)
speak("I am not able to send this email")
elif "send a mail" in query:
try:
speak("What should I say?")
content = takeCommand()
speak("whome should i send")
to = input()
sendEmail(to, content)
speak("Email has been sent !")
except Exception as e:
print(e)
speak("I am not able to send this email")
elif "how are you" in query:
speak("I am fine, Thank you")
speak("How are you, Sir")
elif "fine" in query or "good" in query:
speak("It's good to know that your fine")
elif "change my name to" in query:
query = query.replace("change my name to", "")
assname = query
elif "change name" in query:
speak("What would you like to call me, Sir ")
assname = takeCommand()
speak("Thanks for naming me")
elif "what's your name" in query or "What is your name" in query:
speak("My friends call me")
speak(assname)
print("My friends call me", assname)
elif "exit" in query:
speak("Thanks for giving me your time")
exit()
elif "who made you" in query or "who created you" in query:
speak("I have been created by Gaurav.")
elif "joke" in query:
speak(pyjokes.get_joke())
elif "calculate" in query:
app_id = "Wolframalpha api id"
client = wolframalpha.Client(app_id)
indx = query.lower().split().index("calculate")
query = query.split()[indx + 1 :]
res = client.query(" ".join(query))
answer = next(res.results).text
print("The answer is " + answer)
speak("The answer is " + answer)
elif "search" in query or "play" in query:
query = query.replace("search", "")
query = query.replace("play", "")
webbrowser.open(query)
elif "who i am" in query:
speak("If you talk then definitely your human.")
elif "why you came to world" in query:
speak("Thanks to Gaurav. further It's a secret")
elif "power point presentation" in query:
speak("opening Power Point presentation")
power = r"C:\\Users\\GAURAV\\Desktop\\Minor Project\\Presentation\\Voice Assistant.pptx"
os.startfile(power)
elif "is love" in query:
speak("It is 7th sense that destroy all other senses")
elif "who are you" in query:
speak("I am your virtual assistant created by Gaurav")
elif "reason for you" in query:
speak("I was created as a Minor project by Mister Gaurav ")
elif "change background" in query:
ctypes.windll.user32.SystemParametersInfoW(
20, 0, "Location of wallpaper", 0
)
speak("Background changed successfully")
elif "open bluestack" in query:
appli = r"C:\\ProgramData\\BlueStacks\\Client\\Bluestacks.exe"
os.startfile(appli)
elif "news" in query:
try:
jsonObj = urlopen(
"""https://newsapi.org / v1 / articles?source = the-times-of-india&sortBy = top&apiKey =\\times of India Api key\\"""
)
data = json.load(jsonObj)
i = 1
speak("here are some top news from the times of india")
print("""=============== TIMES OF INDIA ============""" + "\n")
for item in data["articles"]:
print(str(i) + ". " + item["title"] + "\n")
print(item["description"] + "\n")
speak(str(i) + ". " + item["title"] + "\n")
i += 1
except Exception as e:
print(str(e))
elif "lock window" in query:
speak("locking the device")
ctypes.windll.user32.LockWorkStation()
elif "shutdown system" in query:
speak("Hold On a Sec ! Your system is on its way to shut down")
subprocess.call("shutdown / p /f")
elif "empty recycle bin" in query:
winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)
speak("Recycle Bin Recycled")
elif "don't listen" in query or "stop listening" in query:
speak("for how much time you want to stop jarvis from listening commands")
a = int(takeCommand())
time.sleep(a)
print(a)
elif "where is" in query:
query = query.replace("where is", "")
location = query
speak("User asked to Locate")
speak(location)
webbrowser.open("https://www.google.nl / maps / place/" + location + "")
elif "camera" in query or "take a photo" in query:
ec.capture(0, "Jarvis Camera ", "img.jpg")
elif "restart" in query:
subprocess.call(["shutdown", "/r"])
elif "hibernate" in query or "sleep" in query:
speak("Hibernating")
subprocess.call("shutdown / h")
elif "log off" in query or "sign out" in query:
speak("Make sure all the application are closed before sign-out")
time.sleep(5)
subprocess.call(["shutdown", "/l"])
elif "write a note" in query:
speak("What should i write, sir")
note = takeCommand()
file = open("jarvis.txt", "w")
speak("Sir, Should i include date and time")
snfm = takeCommand()
if "yes" in snfm or "sure" in snfm:
strTime = datetime.datetime.now().strftime("% H:% M:% S")
file.write(strTime)
file.write(" :- ")
file.write(note)
else:
file.write(note)
elif "show note" in query:
speak("Showing Notes")
file = open("jarvis.txt", "r")
print(file.read())
speak(file.read(6))
elif "update assistant" in query:
speak(
"After downloading file please replace this file with the downloaded one"
)
url = "# url after uploading file"
r = requests.get(url, stream=True)
with open("Voice.py", "wb") as Pypdf:
total_length = int(r.headers.get("content-length"))
for ch in progress.bar(
r.iter_content(chunk_size=2391975),
expected_size=(total_length / 1024) + 1,
):
if ch:
Pypdf.write(ch)
# NPPR9-FWDCX-D2C8J-H872K-2YT43
elif "jarvis" in query:
wishMe()
speak("Jarvis 1 point o in your service Mister")
speak(assname)
elif "weather" in query:
# Google Open weather website
# to get API of Open weather
api_key = "Api key"
base_url = "http://api.openweathermap.org / data / 2.5 / weather?"
speak(" City name ")
print("City name : ")
city_name = takeCommand()
complete_url = base_url + "appid =" + api_key + "&q =" + city_name
response = requests.get(complete_url)
x = response.json()
if x["code"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
print(
" Temperature (in kelvin unit) = "
+ str(current_temperature)
+ "\n atmospheric pressure (in hPa unit) ="
+ str(current_pressure)
+ "\n humidity (in percentage) = "
+ str(current_humidiy)
+ "\n description = "
+ str(weather_description)
)
else:
speak(" City Not Found ")
elif "send message " in query:
# You need to create an account on Twilio to use this service
account_sid = "Account Sid key"
auth_token = "Auth token"
client = Client(account_sid, auth_token)
message = client.messages.create(
body=takeCommand(), from_="Sender No", to="Receiver No"
)
print(message.sid)
elif "wikipedia" in query:
webbrowser.open("wikipedia.com")
elif "Good Morning" in query:
speak("A warm" + query)
speak("How are you Mister")
speak(assname)
# most asked question from google Assistant
elif "will you be my gf" in query or "will you be my bf" in query:
speak("I'm not sure about, may be you should give me some time")
elif "how are you" in query:
speak("I'm fine, glad you me that")
elif "i love you" in query:
speak("It's hard to understand")
elif "what is" in query or "who is" in query:
# Use the same API key
# that we have generated earlier
client = wolframalpha.Client("API_ID")
res = client.query(query)
try:
print(next(res.results).text)
speak(next(res.results).text)
except StopIteration:
print("No results")
# elif "" in query:
# Command go here
# For adding more commands |
#Output : pip install wolframalpha | Voice Assistant using python
if __name__ == "__main__":
clear = lambda: os.system("cls")
# This Function will clean any
# command before execution of this python file
clear()
wishMe()
username()
while True:
query = takeCommand().lower()
# All the commands said by user will be
# stored here in 'query' and will be
# converted to lower case for easily
# recognition of command
if "wikipedia" in query:
speak("Searching Wikipedia...")
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences=3)
speak("According to Wikipedia")
print(results)
speak(results)
elif "open youtube" in query:
speak("Here you go to Youtube\n")
webbrowser.open("youtube.com")
elif "open google" in query:
speak("Here you go to Google\n")
webbrowser.open("google.com")
elif "open stackoverflow" in query:
speak("Here you go to Stack Over flow.Happy coding")
webbrowser.open("stackoverflow.com")
elif "play music" in query or "play song" in query:
speak("Here you go with music")
# music_dir = "G:\\Song"
music_dir = "C:\\Users\\GAURAV\\Music"
songs = os.listdir(music_dir)
print(songs)
random = os.startfile(os.path.join(music_dir, songs[1]))
elif "the time" in query:
strTime = datetime.datetime.now().strftime("% H:% M:% S")
speak(f"Sir, the time is {strTime}")
elif "open opera" in query:
codePath = (
r"C:\\Users\\GAURAV\\AppData\\Local\\Programs\\Opera\\launcher.exe"
)
os.startfile(codePath)
elif "email to gaurav" in query:
try:
speak("What should I say?")
content = takeCommand()
to = "Receiver email address"
sendEmail(to, content)
speak("Email has been sent !")
except Exception as e:
print(e)
speak("I am not able to send this email")
elif "send a mail" in query:
try:
speak("What should I say?")
content = takeCommand()
speak("whome should i send")
to = input()
sendEmail(to, content)
speak("Email has been sent !")
except Exception as e:
print(e)
speak("I am not able to send this email")
elif "how are you" in query:
speak("I am fine, Thank you")
speak("How are you, Sir")
elif "fine" in query or "good" in query:
speak("It's good to know that your fine")
elif "change my name to" in query:
query = query.replace("change my name to", "")
assname = query
elif "change name" in query:
speak("What would you like to call me, Sir ")
assname = takeCommand()
speak("Thanks for naming me")
elif "what's your name" in query or "What is your name" in query:
speak("My friends call me")
speak(assname)
print("My friends call me", assname)
elif "exit" in query:
speak("Thanks for giving me your time")
exit()
elif "who made you" in query or "who created you" in query:
speak("I have been created by Gaurav.")
elif "joke" in query:
speak(pyjokes.get_joke())
elif "calculate" in query:
app_id = "Wolframalpha api id"
client = wolframalpha.Client(app_id)
indx = query.lower().split().index("calculate")
query = query.split()[indx + 1 :]
res = client.query(" ".join(query))
answer = next(res.results).text
print("The answer is " + answer)
speak("The answer is " + answer)
elif "search" in query or "play" in query:
query = query.replace("search", "")
query = query.replace("play", "")
webbrowser.open(query)
elif "who i am" in query:
speak("If you talk then definitely your human.")
elif "why you came to world" in query:
speak("Thanks to Gaurav. further It's a secret")
elif "power point presentation" in query:
speak("opening Power Point presentation")
power = r"C:\\Users\\GAURAV\\Desktop\\Minor Project\\Presentation\\Voice Assistant.pptx"
os.startfile(power)
elif "is love" in query:
speak("It is 7th sense that destroy all other senses")
elif "who are you" in query:
speak("I am your virtual assistant created by Gaurav")
elif "reason for you" in query:
speak("I was created as a Minor project by Mister Gaurav ")
elif "change background" in query:
ctypes.windll.user32.SystemParametersInfoW(
20, 0, "Location of wallpaper", 0
)
speak("Background changed successfully")
elif "open bluestack" in query:
appli = r"C:\\ProgramData\\BlueStacks\\Client\\Bluestacks.exe"
os.startfile(appli)
elif "news" in query:
try:
jsonObj = urlopen(
"""https://newsapi.org / v1 / articles?source = the-times-of-india&sortBy = top&apiKey =\\times of India Api key\\"""
)
data = json.load(jsonObj)
i = 1
speak("here are some top news from the times of india")
print("""=============== TIMES OF INDIA ============""" + "\n")
for item in data["articles"]:
print(str(i) + ". " + item["title"] + "\n")
print(item["description"] + "\n")
speak(str(i) + ". " + item["title"] + "\n")
i += 1
except Exception as e:
print(str(e))
elif "lock window" in query:
speak("locking the device")
ctypes.windll.user32.LockWorkStation()
elif "shutdown system" in query:
speak("Hold On a Sec ! Your system is on its way to shut down")
subprocess.call("shutdown / p /f")
elif "empty recycle bin" in query:
winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)
speak("Recycle Bin Recycled")
elif "don't listen" in query or "stop listening" in query:
speak("for how much time you want to stop jarvis from listening commands")
a = int(takeCommand())
time.sleep(a)
print(a)
elif "where is" in query:
query = query.replace("where is", "")
location = query
speak("User asked to Locate")
speak(location)
webbrowser.open("https://www.google.nl / maps / place/" + location + "")
elif "camera" in query or "take a photo" in query:
ec.capture(0, "Jarvis Camera ", "img.jpg")
elif "restart" in query:
subprocess.call(["shutdown", "/r"])
elif "hibernate" in query or "sleep" in query:
speak("Hibernating")
subprocess.call("shutdown / h")
elif "log off" in query or "sign out" in query:
speak("Make sure all the application are closed before sign-out")
time.sleep(5)
subprocess.call(["shutdown", "/l"])
elif "write a note" in query:
speak("What should i write, sir")
note = takeCommand()
file = open("jarvis.txt", "w")
speak("Sir, Should i include date and time")
snfm = takeCommand()
if "yes" in snfm or "sure" in snfm:
strTime = datetime.datetime.now().strftime("% H:% M:% S")
file.write(strTime)
file.write(" :- ")
file.write(note)
else:
file.write(note)
elif "show note" in query:
speak("Showing Notes")
file = open("jarvis.txt", "r")
print(file.read())
speak(file.read(6))
elif "update assistant" in query:
speak(
"After downloading file please replace this file with the downloaded one"
)
url = "# url after uploading file"
r = requests.get(url, stream=True)
with open("Voice.py", "wb") as Pypdf:
total_length = int(r.headers.get("content-length"))
for ch in progress.bar(
r.iter_content(chunk_size=2391975),
expected_size=(total_length / 1024) + 1,
):
if ch:
Pypdf.write(ch)
# NPPR9-FWDCX-D2C8J-H872K-2YT43
elif "jarvis" in query:
wishMe()
speak("Jarvis 1 point o in your service Mister")
speak(assname)
elif "weather" in query:
# Google Open weather website
# to get API of Open weather
api_key = "Api key"
base_url = "http://api.openweathermap.org / data / 2.5 / weather?"
speak(" City name ")
print("City name : ")
city_name = takeCommand()
complete_url = base_url + "appid =" + api_key + "&q =" + city_name
response = requests.get(complete_url)
x = response.json()
if x["code"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
print(
" Temperature (in kelvin unit) = "
+ str(current_temperature)
+ "\n atmospheric pressure (in hPa unit) ="
+ str(current_pressure)
+ "\n humidity (in percentage) = "
+ str(current_humidiy)
+ "\n description = "
+ str(weather_description)
)
else:
speak(" City Not Found ")
elif "send message " in query:
# You need to create an account on Twilio to use this service
account_sid = "Account Sid key"
auth_token = "Auth token"
client = Client(account_sid, auth_token)
message = client.messages.create(
body=takeCommand(), from_="Sender No", to="Receiver No"
)
print(message.sid)
elif "wikipedia" in query:
webbrowser.open("wikipedia.com")
elif "Good Morning" in query:
speak("A warm" + query)
speak("How are you Mister")
speak(assname)
# most asked question from google Assistant
elif "will you be my gf" in query or "will you be my bf" in query:
speak("I'm not sure about, may be you should give me some time")
elif "how are you" in query:
speak("I'm fine, glad you me that")
elif "i love you" in query:
speak("It's hard to understand")
elif "what is" in query or "who is" in query:
# Use the same API key
# that we have generated earlier
client = wolframalpha.Client("API_ID")
res = client.query(query)
try:
print(next(res.results).text)
speak(next(res.results).text)
except StopIteration:
print("No results")
# elif "" in query:
# Command go here
# For adding more commands
#Output : pip install wolframalpha
[END] |
Voice search Wikipedia using Python | https://www.geeksforgeeks.org/voice-search-wikipedia-using-python/ | # Python package supporting common text-to-speech engines
import pyttsx3
# For understanding speech
import speech_recognition as sr
# For fetching the answers
# to computational queries
import wolframalpha
# for fetching wikipedia articles
import wikipedia
# Function to search the query
# that is either entered or spoken
# by user
def search(query):
# try is used for searching with wolframAlpha
try:
# Generate your App ID from WolframAlpha
app_id = "Your WolframAlpha App ID here"
client = wolframalpha.Client(app_id)
res = client.query(query)
answer = next(res.results).text
print(answer)
SpeakText("Your answer is " + answer)
# If the query cannot be searched using
# WolframAlpha then it is searched in
# wikipedia
except:
query = query.split(" ")
query = " ".join(query[0:])
SpeakText("I am searching for " + query)
print(wikipedia.summary(query, sentences=3))
SpeakText(wikipedia.summary(query, sentences=3))
# Function to convert text to
# speech
def SpeakText(command):
# Initialize the engine
engine = pyttsx3.init()
engine.say(command)
engine.runAndWait()
# Driver's code
# input query from the user by
# typing or by voice
query = input()
query = query.lower()
# if query is blank then user
# is prompted to speak something.
if query == "":
r = sr.Recognizer()
# uses the default microphone
# as the source to record voice
with sr.Microphone() as source:
print("Say Something ")
# reduces the background disturbances
# and noise for 2 seconds
r.adjust_for_ambient_noise(source, 2)
# listening to source
audio = r.listen(source)
try:
speech = r.recognize_google(audio)
search(speech)
# Handling Exceptions if speech
# is not understood.
except sr.UnknownValueError:
print(
"Google Speech Recognition could not \
understand audio"
)
# Couldn't handle requests, occurs
# mainly because of network errors
except sr.RequestError as e:
print(
"Could not request results from Google \
Speech Recognition service;{0}".format(
e
)
)
else:
search(query) |
#Output :
| Voice search Wikipedia using Python
# Python package supporting common text-to-speech engines
import pyttsx3
# For understanding speech
import speech_recognition as sr
# For fetching the answers
# to computational queries
import wolframalpha
# for fetching wikipedia articles
import wikipedia
# Function to search the query
# that is either entered or spoken
# by user
def search(query):
# try is used for searching with wolframAlpha
try:
# Generate your App ID from WolframAlpha
app_id = "Your WolframAlpha App ID here"
client = wolframalpha.Client(app_id)
res = client.query(query)
answer = next(res.results).text
print(answer)
SpeakText("Your answer is " + answer)
# If the query cannot be searched using
# WolframAlpha then it is searched in
# wikipedia
except:
query = query.split(" ")
query = " ".join(query[0:])
SpeakText("I am searching for " + query)
print(wikipedia.summary(query, sentences=3))
SpeakText(wikipedia.summary(query, sentences=3))
# Function to convert text to
# speech
def SpeakText(command):
# Initialize the engine
engine = pyttsx3.init()
engine.say(command)
engine.runAndWait()
# Driver's code
# input query from the user by
# typing or by voice
query = input()
query = query.lower()
# if query is blank then user
# is prompted to speak something.
if query == "":
r = sr.Recognizer()
# uses the default microphone
# as the source to record voice
with sr.Microphone() as source:
print("Say Something ")
# reduces the background disturbances
# and noise for 2 seconds
r.adjust_for_ambient_noise(source, 2)
# listening to source
audio = r.listen(source)
try:
speech = r.recognize_google(audio)
search(speech)
# Handling Exceptions if speech
# is not understood.
except sr.UnknownValueError:
print(
"Google Speech Recognition could not \
understand audio"
)
# Couldn't handle requests, occurs
# mainly because of network errors
except sr.RequestError as e:
print(
"Could not request results from Google \
Speech Recognition service;{0}".format(
e
)
)
else:
search(query)
#Output :
[END] |
Language Translator Using Google API in Python | https://www.geeksforgeeks.org/language-translator-using-google-api-in-python/ | # To Print all the languages that google
# translator supports
import googletrans
print(googletrans.LANGUAGES) |
#Output : pip install googletrans | Language Translator Using Google API in Python
# To Print all the languages that google
# translator supports
import googletrans
print(googletrans.LANGUAGES)
#Output : pip install googletrans
[END] |
Language Translator Using Google API in Python | https://www.geeksforgeeks.org/language-translator-using-google-api-in-python/ | # Importing necessary modules required
import speech_recognition as spr
from googletrans import Translator
from gtts import gTTS
import os
# Creating Recogniser() class object
recog1 = spr.Recognizer()
# Creating microphone instance
mc = spr.Microphone()
# Capture Voice
with mc as source:
print("Speak 'hello' to initiate the Translation !")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
recog1.adjust_for_ambient_noise(source, duration=0.2)
audio = recog1.listen(source)
MyText = recog1.recognize_google(audio)
MyText = MyText.lower()
# Here initialising the recorder with
# hello, whatever after that hello it
# will recognise it.
if "hello" in MyText:
# Translator method for translation
translator = Translator()
# short form of english in which
# you will speak
from_lang = "en"
# In which we want to convert, short
# form of hindi
to_lang = "hi"
with mc as source:
print("Speak a stentence...")
recog1.adjust_for_ambient_noise(source, duration=0.2)
# Storing the speech into audio variable
audio = recog1.listen(source)
# Using recognize.google() method to
# convert audio into text
get_sentence = recog1.recognize_google(audio)
# Using try and except block to improve
# its efficiency.
try:
# Printing Speech which need to
# be translated.
print("Phase to be Translated :" + get_sentence)
# Using translate() method which requires
# three arguments, 1st the sentence which
# needs to be translated 2nd source language
# and 3rd to which we need to translate in
text_to_translate = translator.translate(
get_sentence, src=from_lang, dest=to_lang
)
# Storing the translated text in text
# variable
text = text_to_translate.text
# Using Google-Text-to-Speech ie, gTTS() method
# to speak the translated text into the
# destination language which is stored in to_lang.
# Also, we have given 3rd argument as False because
# by default it speaks very slowly
speak = gTTS(text=text, lang=to_lang, slow=False)
# Using save() method to save the translated
# speech in capture_voice.mp3
speak.save("captured_voice.mp3")
# Using OS module to run the translated voice.
os.system("start captured_voice.mp3")
# Here we are using except block for UnknownValue
# and Request Error and printing the same to
# provide better service to the user.
except spr.UnknownValueError:
print("Unable to Understand the Input")
except spr.RequestError as e:
print("Unable to provide Required Output".format(e)) |
#Output : pip install googletrans | Language Translator Using Google API in Python
# Importing necessary modules required
import speech_recognition as spr
from googletrans import Translator
from gtts import gTTS
import os
# Creating Recogniser() class object
recog1 = spr.Recognizer()
# Creating microphone instance
mc = spr.Microphone()
# Capture Voice
with mc as source:
print("Speak 'hello' to initiate the Translation !")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
recog1.adjust_for_ambient_noise(source, duration=0.2)
audio = recog1.listen(source)
MyText = recog1.recognize_google(audio)
MyText = MyText.lower()
# Here initialising the recorder with
# hello, whatever after that hello it
# will recognise it.
if "hello" in MyText:
# Translator method for translation
translator = Translator()
# short form of english in which
# you will speak
from_lang = "en"
# In which we want to convert, short
# form of hindi
to_lang = "hi"
with mc as source:
print("Speak a stentence...")
recog1.adjust_for_ambient_noise(source, duration=0.2)
# Storing the speech into audio variable
audio = recog1.listen(source)
# Using recognize.google() method to
# convert audio into text
get_sentence = recog1.recognize_google(audio)
# Using try and except block to improve
# its efficiency.
try:
# Printing Speech which need to
# be translated.
print("Phase to be Translated :" + get_sentence)
# Using translate() method which requires
# three arguments, 1st the sentence which
# needs to be translated 2nd source language
# and 3rd to which we need to translate in
text_to_translate = translator.translate(
get_sentence, src=from_lang, dest=to_lang
)
# Storing the translated text in text
# variable
text = text_to_translate.text
# Using Google-Text-to-Speech ie, gTTS() method
# to speak the translated text into the
# destination language which is stored in to_lang.
# Also, we have given 3rd argument as False because
# by default it speaks very slowly
speak = gTTS(text=text, lang=to_lang, slow=False)
# Using save() method to save the translated
# speech in capture_voice.mp3
speak.save("captured_voice.mp3")
# Using OS module to run the translated voice.
os.system("start captured_voice.mp3")
# Here we are using except block for UnknownValue
# and Request Error and printing the same to
# provide better service to the user.
except spr.UnknownValueError:
print("Unable to Understand the Input")
except spr.RequestError as e:
print("Unable to provide Required Output".format(e))
#Output : pip install googletrans
[END] |
How to make a voice assistant for E-mail in Python? | https://www.geeksforgeeks.org/how-to-make-a-voice-assistant-for-e-mail-in-python/ | from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os
import pyttsx3
import speech_recognition as sr
from datetime import date
# If modifying these scopes, delete the file token.pickle .
# if you run this for the first
# t time it will take you to gmail to choose your account
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]
def speak(text):
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[1].id)
rate = engine.getProperty("rate")
engine.setProperty("rate", rate - 20)
engine.say(text)
engine.runAndWait()
speak("Welcome to mail service")
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
r.pause_threshold = 1
r.adjust_for_ambient_noise(source, duration=1)
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except:
speak("Didn't get that")
return said.lower()
def authenticate_gmail():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.pickle stores the user's
# access and refresh tokens, and is
# created automatically when the authorization
# flow completes for the first
# time.
if os.path.exists("token.pickle"):
with open("token.pickle", "rb") as token:
creds = pickle.load(token)
# If there are no (valid) credentials available,
# let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open("token.pickle", "wb") as token:
pickle.dump(creds, token)
service = build("gmail", "v1", credentials=creds)
return service
def check_mails(service):
# fetching emails of today's date
today = date.today()
today_main = today.strftime("%Y/%m/%d")
# Call the Gmail API
results = (
service.users()
.messages()
.list(
userId="me",
labelIds=["INBOX", "UNREAD"],
q="after:{0} and category:Primary".format(today_main),
)
.execute()
)
# The above code will get emails from primary
# inbox which are unread
messages = results.get("messages", [])
if not messages:
# if no new emails
print("No messages found.")
speak("No messages found.")
else:
m = ""
# if email found
speak("{} new emails found".format(len(messages)))
speak("if you want to read any particular email just type read ")
speak("and for not reading type leave ")
for message in messages:
msg = (
service.users()
.messages()
.get(userId="me", id=message["id"], format="metadata")
.execute()
)
for add in msg["payload"]["headers"]:
if add["name"] == "From":
# fetching sender's email name
a = str(add["value"].split("<")[0])
print(a)
speak("email from" + a)
text = input()
if text == "read":
print(msg["snippet"])
# speak up the mail
speak(msg["snippet"])
else:
speak("email passed")
SERVICE2 = authenticate_gmail()
check_mails(SERVICE2) |
#Output : pip install pyttsx3 | How to make a voice assistant for E-mail in Python?
from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os
import pyttsx3
import speech_recognition as sr
from datetime import date
# If modifying these scopes, delete the file token.pickle .
# if you run this for the first
# t time it will take you to gmail to choose your account
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]
def speak(text):
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[1].id)
rate = engine.getProperty("rate")
engine.setProperty("rate", rate - 20)
engine.say(text)
engine.runAndWait()
speak("Welcome to mail service")
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
r.pause_threshold = 1
r.adjust_for_ambient_noise(source, duration=1)
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except:
speak("Didn't get that")
return said.lower()
def authenticate_gmail():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.pickle stores the user's
# access and refresh tokens, and is
# created automatically when the authorization
# flow completes for the first
# time.
if os.path.exists("token.pickle"):
with open("token.pickle", "rb") as token:
creds = pickle.load(token)
# If there are no (valid) credentials available,
# let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open("token.pickle", "wb") as token:
pickle.dump(creds, token)
service = build("gmail", "v1", credentials=creds)
return service
def check_mails(service):
# fetching emails of today's date
today = date.today()
today_main = today.strftime("%Y/%m/%d")
# Call the Gmail API
results = (
service.users()
.messages()
.list(
userId="me",
labelIds=["INBOX", "UNREAD"],
q="after:{0} and category:Primary".format(today_main),
)
.execute()
)
# The above code will get emails from primary
# inbox which are unread
messages = results.get("messages", [])
if not messages:
# if no new emails
print("No messages found.")
speak("No messages found.")
else:
m = ""
# if email found
speak("{} new emails found".format(len(messages)))
speak("if you want to read any particular email just type read ")
speak("and for not reading type leave ")
for message in messages:
msg = (
service.users()
.messages()
.get(userId="me", id=message["id"], format="metadata")
.execute()
)
for add in msg["payload"]["headers"]:
if add["name"] == "From":
# fetching sender's email name
a = str(add["value"].split("<")[0])
print(a)
speak("email from" + a)
text = input()
if text == "read":
print(msg["snippet"])
# speak up the mail
speak(msg["snippet"])
else:
speak("email passed")
SERVICE2 = authenticate_gmail()
check_mails(SERVICE2)
#Output : pip install pyttsx3
[END] |
Voice Assistant for Movies using Python | https://www.geeksforgeeks.org/voice-assistant-for-movies-using-python/ | # importing all required libraries
import imdb
import pyttsx3
import speech_recognition as sr
import datetime
# Function for speaking
def speak(text):
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[1].id)
rate = engine.getProperty("rate")
engine.setProperty("rate", rate - 20)
engine.say(text)
engine.runAndWait()
# calling the speak() function
speak("Say the movie name")
# Function to get input in the audio format
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
r.pause_threshold = 1
r.adjust_for_ambient_noise(source, duration=1)
audio = r.listen(source)
said = ""
try:
# will recognize the input
said = r.recognize_google(audio)
print(said)
except:
speak("Didn't get that")
# will return the input in lowercase
return said.lower()
# Function for searching movie
def search_movie():
# gathering information from IMDb
moviesdb = imdb.IMDb()
# search for title
text = get_audio()
# passing input for searching movie
movies = moviesdb.search_movie(text)
speak("Searching for " + text)
if len(movies) == 0:
speak("No result found")
else:
speak("I found these:")
for movie in movies:
title = movie["title"]
year = movie["year"]
# speaking title with releasing year
speak(f"{title}-{year}")
info = movie.getID()
movie = moviesdb.get_movie(info)
title = movie["title"]
year = movie["year"]
rating = movie["rating"]
plot = movie["plot outline"]
# the below if-else is for past and future release
if year < int(datetime.datetime.now().strftime("%Y")):
speak(
f"{title}was released in {year} has IMDB rating of {rating}.\
The plot summary of movie is{plot}"
)
print(
f"{title}was released in {year} has IMDB rating of {rating}.\
The plot summary of movie is{plot}"
)
break
else:
speak(
f"{title}will release in {year} has IMDB rating of {rating}.\
The plot summary of movie is{plot}"
)
print(
f"{title}will release in {year} has IMDB rating of {rating}.\
The plot summary of movie is{plot}"
)
break
search_movie() |
#Output : pip install IMDbPY | Voice Assistant for Movies using Python
# importing all required libraries
import imdb
import pyttsx3
import speech_recognition as sr
import datetime
# Function for speaking
def speak(text):
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[1].id)
rate = engine.getProperty("rate")
engine.setProperty("rate", rate - 20)
engine.say(text)
engine.runAndWait()
# calling the speak() function
speak("Say the movie name")
# Function to get input in the audio format
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
r.pause_threshold = 1
r.adjust_for_ambient_noise(source, duration=1)
audio = r.listen(source)
said = ""
try:
# will recognize the input
said = r.recognize_google(audio)
print(said)
except:
speak("Didn't get that")
# will return the input in lowercase
return said.lower()
# Function for searching movie
def search_movie():
# gathering information from IMDb
moviesdb = imdb.IMDb()
# search for title
text = get_audio()
# passing input for searching movie
movies = moviesdb.search_movie(text)
speak("Searching for " + text)
if len(movies) == 0:
speak("No result found")
else:
speak("I found these:")
for movie in movies:
title = movie["title"]
year = movie["year"]
# speaking title with releasing year
speak(f"{title}-{year}")
info = movie.getID()
movie = moviesdb.get_movie(info)
title = movie["title"]
year = movie["year"]
rating = movie["rating"]
plot = movie["plot outline"]
# the below if-else is for past and future release
if year < int(datetime.datetime.now().strftime("%Y")):
speak(
f"{title}was released in {year} has IMDB rating of {rating}.\
The plot summary of movie is{plot}"
)
print(
f"{title}was released in {year} has IMDB rating of {rating}.\
The plot summary of movie is{plot}"
)
break
else:
speak(
f"{title}will release in {year} has IMDB rating of {rating}.\
The plot summary of movie is{plot}"
)
print(
f"{title}will release in {year} has IMDB rating of {rating}.\
The plot summary of movie is{plot}"
)
break
search_movie()
#Output : pip install IMDbPY
[END] |
8-bit game using pygame | https://www.geeksforgeeks.org/8-bit-game-using-pygame/ | # Python program to demonstrate
# 8 bit game
import pygame
import sys
import random
# initialize the constructor
pygame.init()
res = (720, 720)
# randomly assigns a value to variables
# ranging from lower limit to upper
c1 = random.randint(125, 255)
c2 = random.randint(0, 255)
c3 = random.randint(0, 255)
screen = pygame.display.set_mode(res)
clock = pygame.time.Clock()
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
color_list = [red, green, blue]
colox_c1 = 0
colox_c2 = 0
colox_c3 = 254
colox_c4 = 254
# randomly assigns a colour from color_list
# to player
player_c = random.choice(color_list)
# light shade of menu buttons
startl = (169, 169, 169)
# dark shade of menu buttons
startd = (100, 100, 100)
white = (255, 255, 255)
start = (255, 255, 255)
width = screen.get_width()
height = screen.get_height()
# initial X position of player
lead_x = 40
# initial y position of player
lead_y = height / 2
x = 300
y = 290
width1 = 100
height1 = 40
enemy_size = 50
# defining a font
smallfont = pygame.font.SysFont("Corbel", 35)
# texts to be rendered on screen
text = smallfont.render("Start", True, white)
text1 = smallfont.render("Options", True, white)
exit1 = smallfont.render("Exit", True, white)
# game title
colox = smallfont.render("Colox", True, (c3, c2, c1))
x1 = random.randint(width / 2, width)
y1 = random.randint(100, height / 2)
x2 = 40
y2 = 40
speed = 15
# score of the player
count = 0
rgb = random.choice(color_list)
# enemy position
e_p = [width, random.randint(50, height - 50)]
e1_p = [random.randint(width, width + 100), random.randint(50, height - 100)]
# function for game_over
def game_over():
while True:
# if the player clicks the cross
# button
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
if ev.type == pygame.MOUSEBUTTONDOWN:
if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] < height - 80:
pygame.quit()
if ev.type == pygame.MOUSEBUTTONDOWN:
if (
width - 180 < mouse1[0] < width - 100
and height - 100 < mouse1[1] < height - 80
):
# calling function game
game(lead_x, lead_y, speed, count)
# fills the screen with specified colour
screen.fill((65, 25, 64))
smallfont = pygame.font.SysFont("Corbel", 60)
smallfont1 = pygame.font.SysFont("Corbel", 25)
game_over = smallfont.render("GAME OVER", True, white)
game_exit = smallfont1.render("exit", True, white)
restart = smallfont1.render("restart", True, white)
mouse1 = pygame.mouse.get_pos()
# exit
if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] < height - 80:
pygame.draw.rect(screen, startl, [100, height - 100, 40, 20])
else:
pygame.draw.rect(screen, startd, [100, height - 100, 40, 20])
# restart
if (
width - 180 < mouse1[0] < width - 100
and height - 100 < mouse1[1] < height - 80
):
pygame.draw.rect(screen, startl, [width - 180, height - 100, 80, 20])
else:
pygame.draw.rect(screen, startd, [width - 180, height - 100, 80, 20])
screen.blit(game_exit, (100, height - 100))
# superimposes one object on other
screen.blit(restart, (width - 180, height - 100))
screen.blit(game_over, (width / 2 - 150, 295))
# updates frames of the game
pygame.display.update()
pygame.draw.rect(screen, startd, [100, height - 100, 40, 20])
pygame.draw.rect(screen, startd, [width - 180, height - 100, 40, 50])
# function for body of the game
def game(
lead_y,
lead_X,
speed,
count,
):
while True:
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
# player control
# keeps track of the key pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
# if up key is pressed then the players
# y pos will decrement by 10
lead_y -= 10
if keys[pygame.K_DOWN]:
# if down key is pressed then the y pos
# of the player is incremented by 10
lead_y += 10
screen.fill((65, 25, 64))
clock.tick(speed)
# draws a rectangle on the screen
rect = pygame.draw.rect(screen, player_c, [lead_x, lead_y, 40, 40])
pygame.draw.rect(screen, (c1, c2, c3), [0, 0, width, 40])
pygame.draw.rect(screen, (c3, c2, c1), [0, 680, width, 40])
pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40])
smallfont = pygame.font.SysFont("Corbel", 35)
exit2 = smallfont.render("Exit", True, white)
# exit
# gets the X and y position of mouse
# pointer and stores them as a tuple
mouse = pygame.mouse.get_pos()
if width - 100 < mouse[0] < width and 0 < mouse[1] < 40:
pygame.draw.rect(screen, startl, [width - 100, 0, 100, 40])
else:
pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40])
if width - 100 < mouse[0] < width and 0 < mouse[1] < 40:
if ev.type == pygame.MOUSEBUTTONDOWN:
pygame.quit()
# enemy position
if e_p[0] > 0 and e_p[0] <= width:
# if the enemy block's X coordinate is between 0 and
# the width of the screen the X value gets
# decremented by 10
e_p[0] -= 10
else:
if e_p[1] <= 40 or e_p[1] >= height - 40:
e_p[1] = height / 2
if e1_p[1] <= 40 or e1_p[1] >= height - 40:
e1_p[1] = random.randint(40, height - 40)
e_p[1] = random.randint(enemy_size, height - enemy_size)
e_p[0] = width
# game over
# collision detection
if lead_x <= e_p[0] <= lead_x + 40 and lead_y >= e_p[1] >= lead_y - 40:
game_over()
# checks if the player block has collided with the enemy block
if (
lead_y <= e_p[1] + enemy_size <= lead_y + 40
and lead_x <= e_p[0] <= lead_x + 40
):
game_over()
pygame.draw.rect(screen, red, [e_p[0], e_p[1], enemy_size, enemy_size])
if e1_p[0] > 0 and e1_p[0] <= width + 100:
e1_p[0] -= 10
else:
if e1_p[1] <= 40 or e1_p[1] >= height - 40:
e1_p[1] = height / 2
e1_p[1] = random.randint(enemy_size, height - 40)
e1_p[0] = width + 100
if lead_x <= e1_p[0] <= lead_x + 40 and lead_y >= e1_p[1] >= lead_y - 40:
e1_p[0] = width + 100
e1_p[1] = random.randint(40, height - 40)
count += 1
speed += 1
if (
lead_y <= e1_p[1] + enemy_size <= lead_y + 40
and lead_x <= e1_p[0] <= lead_x + 40
):
e1_p[0] = width + 100
e1_p[1] = random.randint(40, height - 40)
# increases the score when blue box is hit
count += 1
# increases the speed as score increases
speed += 1
if count >= 45:
# freezes the game FPS to 60 if
# score reaches 45 or more
speed = 60
if lead_y <= 38 or lead_y >= height - 38:
game_over()
if e1_p[0] <= 0:
game_over()
pygame.draw.rect(screen, blue, [e1_p[0], e1_p[1], enemy_size, enemy_size])
score1 = smallfont.render("Score:", True, white)
screen.blit(score1, (width - 120, height - 40))
screen.blit(exit2, (width - 80, 0))
pygame.display.update()
# intro
def intro(
colox_c1,
colox_c2,
colox,
exit1,
text1,
text,
):
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
screen.fill((65, 25, 64))
mouse = pygame.mouse.get_pos()
# start screen
if x < mouse[0] < x + width1 and y < mouse[1] < y + height1:
# if mouse is hovered on a button
# its colour shade becomes lighter
pygame.draw.rect(screen, startl, [x, y, width1, height1])
else:
if x < mouse[0] < x + width1 + 40 and y + 70 < mouse[1] < y + 70 + height1:
pygame.draw.rect(screen, startl, [x, y + 70, width1 + 40, height1])
else:
if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1:
pygame.draw.rect(screen, startl, [x, y + 140, width1, height1])
else:
pygame.draw.rect(screen, startd, [x, y, width1, height1])
pygame.draw.rect(screen, startd, [x, y + 70, width1 + 40, height1])
pygame.draw.rect(screen, startd, [x, y + 140, width1, height1])
# start button
if event.type == pygame.MOUSEBUTTONDOWN:
if x < mouse[0] < x + width1 and y < mouse[1] < y + height1:
# music()
game(lead_y, lead_x, speed, count)
if event.type == pygame.MOUSEBUTTONDOWN:
if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1:
pygame.quit()
# this handles the colour breezing effect
if 0 <= colox_c1 <= 254 or 0 <= colox_c2 <= 254:
colox_c1 += 1
colox_c2 += 1
if colox_c1 >= 254 or colox_c2 >= 254:
colox_c1 = c3
colox_c2 = c3
pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [0, 0, 40, height])
pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [width - 40, 0, 40, height])
smallfont = pygame.font.SysFont("Corbel", 35)
sig = smallfont.render("Designed by :- Antriksh", True, white)
text = smallfont.render("Start", True, white)
text1 = smallfont.render("Options", True, white)
exit1 = smallfont.render("Exit", True, white)
colox = smallfont.render("Colox", True, (c1, colox_c1, colox_c2))
screen.blit(colox, (312, 50))
screen.blit(text, (312, 295))
screen.blit(text1, (312, 365))
screen.blit(exit1, (312, 435))
screen.blit(sig, (320, height - 50))
clock.tick(60)
pygame.display.update()
intro(
colox_c1,
colox_c2,
colox,
exit1,
text1,
text,
) |
#Output : pip install pygame | 8-bit game using pygame
# Python program to demonstrate
# 8 bit game
import pygame
import sys
import random
# initialize the constructor
pygame.init()
res = (720, 720)
# randomly assigns a value to variables
# ranging from lower limit to upper
c1 = random.randint(125, 255)
c2 = random.randint(0, 255)
c3 = random.randint(0, 255)
screen = pygame.display.set_mode(res)
clock = pygame.time.Clock()
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
color_list = [red, green, blue]
colox_c1 = 0
colox_c2 = 0
colox_c3 = 254
colox_c4 = 254
# randomly assigns a colour from color_list
# to player
player_c = random.choice(color_list)
# light shade of menu buttons
startl = (169, 169, 169)
# dark shade of menu buttons
startd = (100, 100, 100)
white = (255, 255, 255)
start = (255, 255, 255)
width = screen.get_width()
height = screen.get_height()
# initial X position of player
lead_x = 40
# initial y position of player
lead_y = height / 2
x = 300
y = 290
width1 = 100
height1 = 40
enemy_size = 50
# defining a font
smallfont = pygame.font.SysFont("Corbel", 35)
# texts to be rendered on screen
text = smallfont.render("Start", True, white)
text1 = smallfont.render("Options", True, white)
exit1 = smallfont.render("Exit", True, white)
# game title
colox = smallfont.render("Colox", True, (c3, c2, c1))
x1 = random.randint(width / 2, width)
y1 = random.randint(100, height / 2)
x2 = 40
y2 = 40
speed = 15
# score of the player
count = 0
rgb = random.choice(color_list)
# enemy position
e_p = [width, random.randint(50, height - 50)]
e1_p = [random.randint(width, width + 100), random.randint(50, height - 100)]
# function for game_over
def game_over():
while True:
# if the player clicks the cross
# button
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
if ev.type == pygame.MOUSEBUTTONDOWN:
if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] < height - 80:
pygame.quit()
if ev.type == pygame.MOUSEBUTTONDOWN:
if (
width - 180 < mouse1[0] < width - 100
and height - 100 < mouse1[1] < height - 80
):
# calling function game
game(lead_x, lead_y, speed, count)
# fills the screen with specified colour
screen.fill((65, 25, 64))
smallfont = pygame.font.SysFont("Corbel", 60)
smallfont1 = pygame.font.SysFont("Corbel", 25)
game_over = smallfont.render("GAME OVER", True, white)
game_exit = smallfont1.render("exit", True, white)
restart = smallfont1.render("restart", True, white)
mouse1 = pygame.mouse.get_pos()
# exit
if 100 < mouse1[0] < 140 and height - 100 < mouse1[1] < height - 80:
pygame.draw.rect(screen, startl, [100, height - 100, 40, 20])
else:
pygame.draw.rect(screen, startd, [100, height - 100, 40, 20])
# restart
if (
width - 180 < mouse1[0] < width - 100
and height - 100 < mouse1[1] < height - 80
):
pygame.draw.rect(screen, startl, [width - 180, height - 100, 80, 20])
else:
pygame.draw.rect(screen, startd, [width - 180, height - 100, 80, 20])
screen.blit(game_exit, (100, height - 100))
# superimposes one object on other
screen.blit(restart, (width - 180, height - 100))
screen.blit(game_over, (width / 2 - 150, 295))
# updates frames of the game
pygame.display.update()
pygame.draw.rect(screen, startd, [100, height - 100, 40, 20])
pygame.draw.rect(screen, startd, [width - 180, height - 100, 40, 50])
# function for body of the game
def game(
lead_y,
lead_X,
speed,
count,
):
while True:
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
# player control
# keeps track of the key pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
# if up key is pressed then the players
# y pos will decrement by 10
lead_y -= 10
if keys[pygame.K_DOWN]:
# if down key is pressed then the y pos
# of the player is incremented by 10
lead_y += 10
screen.fill((65, 25, 64))
clock.tick(speed)
# draws a rectangle on the screen
rect = pygame.draw.rect(screen, player_c, [lead_x, lead_y, 40, 40])
pygame.draw.rect(screen, (c1, c2, c3), [0, 0, width, 40])
pygame.draw.rect(screen, (c3, c2, c1), [0, 680, width, 40])
pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40])
smallfont = pygame.font.SysFont("Corbel", 35)
exit2 = smallfont.render("Exit", True, white)
# exit
# gets the X and y position of mouse
# pointer and stores them as a tuple
mouse = pygame.mouse.get_pos()
if width - 100 < mouse[0] < width and 0 < mouse[1] < 40:
pygame.draw.rect(screen, startl, [width - 100, 0, 100, 40])
else:
pygame.draw.rect(screen, startd, [width - 100, 0, 100, 40])
if width - 100 < mouse[0] < width and 0 < mouse[1] < 40:
if ev.type == pygame.MOUSEBUTTONDOWN:
pygame.quit()
# enemy position
if e_p[0] > 0 and e_p[0] <= width:
# if the enemy block's X coordinate is between 0 and
# the width of the screen the X value gets
# decremented by 10
e_p[0] -= 10
else:
if e_p[1] <= 40 or e_p[1] >= height - 40:
e_p[1] = height / 2
if e1_p[1] <= 40 or e1_p[1] >= height - 40:
e1_p[1] = random.randint(40, height - 40)
e_p[1] = random.randint(enemy_size, height - enemy_size)
e_p[0] = width
# game over
# collision detection
if lead_x <= e_p[0] <= lead_x + 40 and lead_y >= e_p[1] >= lead_y - 40:
game_over()
# checks if the player block has collided with the enemy block
if (
lead_y <= e_p[1] + enemy_size <= lead_y + 40
and lead_x <= e_p[0] <= lead_x + 40
):
game_over()
pygame.draw.rect(screen, red, [e_p[0], e_p[1], enemy_size, enemy_size])
if e1_p[0] > 0 and e1_p[0] <= width + 100:
e1_p[0] -= 10
else:
if e1_p[1] <= 40 or e1_p[1] >= height - 40:
e1_p[1] = height / 2
e1_p[1] = random.randint(enemy_size, height - 40)
e1_p[0] = width + 100
if lead_x <= e1_p[0] <= lead_x + 40 and lead_y >= e1_p[1] >= lead_y - 40:
e1_p[0] = width + 100
e1_p[1] = random.randint(40, height - 40)
count += 1
speed += 1
if (
lead_y <= e1_p[1] + enemy_size <= lead_y + 40
and lead_x <= e1_p[0] <= lead_x + 40
):
e1_p[0] = width + 100
e1_p[1] = random.randint(40, height - 40)
# increases the score when blue box is hit
count += 1
# increases the speed as score increases
speed += 1
if count >= 45:
# freezes the game FPS to 60 if
# score reaches 45 or more
speed = 60
if lead_y <= 38 or lead_y >= height - 38:
game_over()
if e1_p[0] <= 0:
game_over()
pygame.draw.rect(screen, blue, [e1_p[0], e1_p[1], enemy_size, enemy_size])
score1 = smallfont.render("Score:", True, white)
screen.blit(score1, (width - 120, height - 40))
screen.blit(exit2, (width - 80, 0))
pygame.display.update()
# intro
def intro(
colox_c1,
colox_c2,
colox,
exit1,
text1,
text,
):
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
screen.fill((65, 25, 64))
mouse = pygame.mouse.get_pos()
# start screen
if x < mouse[0] < x + width1 and y < mouse[1] < y + height1:
# if mouse is hovered on a button
# its colour shade becomes lighter
pygame.draw.rect(screen, startl, [x, y, width1, height1])
else:
if x < mouse[0] < x + width1 + 40 and y + 70 < mouse[1] < y + 70 + height1:
pygame.draw.rect(screen, startl, [x, y + 70, width1 + 40, height1])
else:
if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1:
pygame.draw.rect(screen, startl, [x, y + 140, width1, height1])
else:
pygame.draw.rect(screen, startd, [x, y, width1, height1])
pygame.draw.rect(screen, startd, [x, y + 70, width1 + 40, height1])
pygame.draw.rect(screen, startd, [x, y + 140, width1, height1])
# start button
if event.type == pygame.MOUSEBUTTONDOWN:
if x < mouse[0] < x + width1 and y < mouse[1] < y + height1:
# music()
game(lead_y, lead_x, speed, count)
if event.type == pygame.MOUSEBUTTONDOWN:
if x < mouse[0] < width1 + x and y + 140 < mouse[1] < y + 140 + height1:
pygame.quit()
# this handles the colour breezing effect
if 0 <= colox_c1 <= 254 or 0 <= colox_c2 <= 254:
colox_c1 += 1
colox_c2 += 1
if colox_c1 >= 254 or colox_c2 >= 254:
colox_c1 = c3
colox_c2 = c3
pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [0, 0, 40, height])
pygame.draw.rect(screen, (c2, colox_c1, colox_c2), [width - 40, 0, 40, height])
smallfont = pygame.font.SysFont("Corbel", 35)
sig = smallfont.render("Designed by :- Antriksh", True, white)
text = smallfont.render("Start", True, white)
text1 = smallfont.render("Options", True, white)
exit1 = smallfont.render("Exit", True, white)
colox = smallfont.render("Colox", True, (c1, colox_c1, colox_c2))
screen.blit(colox, (312, 50))
screen.blit(text, (312, 295))
screen.blit(text1, (312, 365))
screen.blit(exit1, (312, 435))
screen.blit(sig, (320, height - 50))
clock.tick(60)
pygame.display.update()
intro(
colox_c1,
colox_c2,
colox,
exit1,
text1,
text,
)
#Output : pip install pygame
[END] |
Caller ID Lookup using Python | https://www.geeksforgeeks.org/caller-id-lookup-using-python/ | # import module
import requests
import pandas as pd
from bs4 import BeautifulSoup
# link for extract html data
# Making a GET request
def getdata(url):
r = requests.get(url)
return r.text
# API key
# Enter your own API key instead of 'YOUR API KEY'
api = "YOUR API KEY"
# number and country code
number = "9852638787"
country = "IN"
# pass Your API, number and country code
# in getdata function
htmldata = getdata(
"http://apilayer.net/api/validate?access_key="
+ api
+ "&number="
+ number
+ "&country_code="
+ country
+ "&format=1"
)
soup = BeautifulSoup(htmldata, "html.parser")
print(soup) |
#Output : pip install bs4 | Caller ID Lookup using Python
# import module
import requests
import pandas as pd
from bs4 import BeautifulSoup
# link for extract html data
# Making a GET request
def getdata(url):
r = requests.get(url)
return r.text
# API key
# Enter your own API key instead of 'YOUR API KEY'
api = "YOUR API KEY"
# number and country code
number = "9852638787"
country = "IN"
# pass Your API, number and country code
# in getdata function
htmldata = getdata(
"http://apilayer.net/api/validate?access_key="
+ api
+ "&number="
+ number
+ "&country_code="
+ country
+ "&format=1"
)
soup = BeautifulSoup(htmldata, "html.parser")
print(soup)
#Output : pip install bs4
[END] |
Tweet using Python | https://www.geeksforgeeks.org/tweet-using-python/ | # importing the module
import tweepy
# personal details
consumer_key = "xxxxxxxxxxxxxxxx"
consumer_secret = "xxxxxxxxxxxxxxxx"
access_token = "xxxxxxxxxxxxxxxx"
access_token_secret = "xxxxxxxxxxxxxxxx"
# authentication of consumer key and secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# authentication of access token and secret
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# update the status
api.update_status(status="Hello Everyone !") |
#Output :
| Tweet using Python
# importing the module
import tweepy
# personal details
consumer_key = "xxxxxxxxxxxxxxxx"
consumer_secret = "xxxxxxxxxxxxxxxx"
access_token = "xxxxxxxxxxxxxxxx"
access_token_secret = "xxxxxxxxxxxxxxxx"
# authentication of consumer key and secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# authentication of access token and secret
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# update the status
api.update_status(status="Hello Everyone !")
#Output :
[END] |
Tweet using Python | https://www.geeksforgeeks.org/tweet-using-python/ | time.sleep(600) # waits for 600 seconds |
#Output :
| Tweet using Python
time.sleep(600) # waits for 600 seconds
#Output :
[END] |
Tweet using Python | https://www.geeksforgeeks.org/tweet-using-python/ | # importing the module
import tweepy
# personal information
consumer_key = "xxxxxxxxxxxxxxxx"
consumer_secret = "xxxxxxxxxxxxxxxx"
access_token = "xxxxxxxxxxxxxxxx"
access_token_secret = "xxxxxxxxxxxxxxxx"
# authentication
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweet = "Text part of the tweet" # toDo
image_path = "path of the image" # toDo
# to attach the media file
status = api.update_with_media(image_path, tweet)
api.update_status(status=tweet) |
#Output :
| Tweet using Python
# importing the module
import tweepy
# personal information
consumer_key = "xxxxxxxxxxxxxxxx"
consumer_secret = "xxxxxxxxxxxxxxxx"
access_token = "xxxxxxxxxxxxxxxx"
access_token_secret = "xxxxxxxxxxxxxxxx"
# authentication
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweet = "Text part of the tweet" # toDo
image_path = "path of the image" # toDo
# to attach the media file
status = api.update_with_media(image_path, tweet)
api.update_status(status=tweet)
#Output :
[END] |
How to make Flappy Bird Game in Pygame? | https://www.geeksforgeeks.org/how-to-make-flappy-bird-game-in-pygame/ | # For generating random height of pipes
import random
import sys
import pygame
from pygame.locals import *
# Global Variables for the game
window_width = 600
window_height = 499
# set height and width of window
window = pygame.display.set_mode((window_width, window_height))
elevation = window_height * 0.8
game_images = {}
framepersecond = 32
pipeimage = "images/pipe.png"
background_image = "images/background.jpg"
birdplayer_image = "/images/bird.png"
sealevel_image = "/images/base.jfif" |
#Output : pip install pygame | How to make Flappy Bird Game in Pygame?
# For generating random height of pipes
import random
import sys
import pygame
from pygame.locals import *
# Global Variables for the game
window_width = 600
window_height = 499
# set height and width of window
window = pygame.display.set_mode((window_width, window_height))
elevation = window_height * 0.8
game_images = {}
framepersecond = 32
pipeimage = "images/pipe.png"
background_image = "images/background.jpg"
birdplayer_image = "/images/bird.png"
sealevel_image = "/images/base.jfif"
#Output : pip install pygame
[END] |
How to make Flappy Bird Game in Pygame? | https://www.geeksforgeeks.org/how-to-make-flappy-bird-game-in-pygame/ | # program where the game starts
if __name__ == "__main__":
# For initializing modules of pygame library
pygame.init()
framepersecond_clock = pygame.time.Clock()
# Sets the title on top of game window
pygame.display.set_caption("Flappy Bird Game")
# Load all the images which we will use in the game
# images for displaying score
game_images["scoreimages"] = (
pygame.image.load("images/0.png").convert_alpha(),
pygame.image.load("images/1.png").convert_alpha(),
pygame.image.load("images/2.png").convert_alpha(),
pygame.image.load("images/3.png").convert_alpha(),
pygame.image.load("images/4.png").convert_alpha(),
pygame.image.load("images/5.png").convert_alpha(),
pygame.image.load("images/6.png").convert_alpha(),
pygame.image.load("images/7.png").convert_alpha(),
pygame.image.load("images/8.png").convert_alpha(),
pygame.image.load("images/9.png").convert_alpha(),
)
game_images["flappybird"] = pygame.image.load(birdplayer_image).convert_alpha()
game_images["sea_level"] = pygame.image.load(sealevel_image).convert_alpha()
game_images["background"] = pygame.image.load(background_image).convert_alpha()
game_images["pipeimage"] = (
pygame.transform.rotate(pygame.image.load(pipeimage).convert_alpha(), 180),
pygame.image.load(pipeimage).convert_alpha(),
)
print("WELCOME TO THE FLAPPY BIRD GAME")
print("Press space or enter to start the game") |
#Output : pip install pygame | How to make Flappy Bird Game in Pygame?
# program where the game starts
if __name__ == "__main__":
# For initializing modules of pygame library
pygame.init()
framepersecond_clock = pygame.time.Clock()
# Sets the title on top of game window
pygame.display.set_caption("Flappy Bird Game")
# Load all the images which we will use in the game
# images for displaying score
game_images["scoreimages"] = (
pygame.image.load("images/0.png").convert_alpha(),
pygame.image.load("images/1.png").convert_alpha(),
pygame.image.load("images/2.png").convert_alpha(),
pygame.image.load("images/3.png").convert_alpha(),
pygame.image.load("images/4.png").convert_alpha(),
pygame.image.load("images/5.png").convert_alpha(),
pygame.image.load("images/6.png").convert_alpha(),
pygame.image.load("images/7.png").convert_alpha(),
pygame.image.load("images/8.png").convert_alpha(),
pygame.image.load("images/9.png").convert_alpha(),
)
game_images["flappybird"] = pygame.image.load(birdplayer_image).convert_alpha()
game_images["sea_level"] = pygame.image.load(sealevel_image).convert_alpha()
game_images["background"] = pygame.image.load(background_image).convert_alpha()
game_images["pipeimage"] = (
pygame.transform.rotate(pygame.image.load(pipeimage).convert_alpha(), 180),
pygame.image.load(pipeimage).convert_alpha(),
)
print("WELCOME TO THE FLAPPY BIRD GAME")
print("Press space or enter to start the game")
#Output : pip install pygame
[END] |
How to make Flappy Bird Game in Pygame? | https://www.geeksforgeeks.org/how-to-make-flappy-bird-game-in-pygame/ | while True:
# sets the coordinates of flappy bird
horizontal = int(window_width / 5)
vertical = int((window_height - game_images["flappybird"].get_height()) / 2)
# for selevel
ground = 0
while True:
for event in pygame.event.get():
# if user clicks on cross button, close the game
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
# Exit the program
sys.exit()
# If the user presses space or up key,
# start the game for them
elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
flappygame()
# if user doesn't press anykey Nothing happen
else:
window.blit(game_images["background"], (0, 0))
window.blit(game_images["flappybird"], (horizontal, vertical))
window.blit(game_images["sea_level"], (ground, elevation))
# Just Refresh the screen
pygame.display.update()
# set the rate of frame per second
framepersecond_clock.tick(framepersecond) |
#Output : pip install pygame | How to make Flappy Bird Game in Pygame?
while True:
# sets the coordinates of flappy bird
horizontal = int(window_width / 5)
vertical = int((window_height - game_images["flappybird"].get_height()) / 2)
# for selevel
ground = 0
while True:
for event in pygame.event.get():
# if user clicks on cross button, close the game
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
# Exit the program
sys.exit()
# If the user presses space or up key,
# start the game for them
elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
flappygame()
# if user doesn't press anykey Nothing happen
else:
window.blit(game_images["background"], (0, 0))
window.blit(game_images["flappybird"], (horizontal, vertical))
window.blit(game_images["sea_level"], (ground, elevation))
# Just Refresh the screen
pygame.display.update()
# set the rate of frame per second
framepersecond_clock.tick(framepersecond)
#Output : pip install pygame
[END] |
How to make Flappy Bird Game in Pygame? | https://www.geeksforgeeks.org/how-to-make-flappy-bird-game-in-pygame/ | def createPipe():
offset = window_height / 3
pipeHeight = game_images["pipeimage"][0].get_height()
# generating random height of pipes
y2 = offset + random.randrange(
0, int(window_height - game_images["sea_level"].get_height() - 1.2 * offset)
)
pipeX = window_width + 10
y1 = pipeHeight - y2 + offset
pipe = [
# upper Pipe
{"x": pipeX, "y": -y1},
# lower Pipe
{"x": pipeX, "y": y2},
]
return pipe |
#Output : pip install pygame | How to make Flappy Bird Game in Pygame?
def createPipe():
offset = window_height / 3
pipeHeight = game_images["pipeimage"][0].get_height()
# generating random height of pipes
y2 = offset + random.randrange(
0, int(window_height - game_images["sea_level"].get_height() - 1.2 * offset)
)
pipeX = window_width + 10
y1 = pipeHeight - y2 + offset
pipe = [
# upper Pipe
{"x": pipeX, "y": -y1},
# lower Pipe
{"x": pipeX, "y": y2},
]
return pipe
#Output : pip install pygame
[END] |
How to make Flappy Bird Game in Pygame? | https://www.geeksforgeeks.org/how-to-make-flappy-bird-game-in-pygame/ | # Checking if bird is above the sealevel.def isGameOver(horizontal, vertical, up_pipes, down_pipes):????????????????????????if vertical > elevation - 25 or vertical < 0:??????????????????????????????????????????????????????return True????????????????????????????????????# Checking if bird hits the upper pipe or not????????????????????????for pipe in up_pipes:????????????????????????????????????????????????????????????????????????pipeHeight = game_images['pipeimage'][0].get_height()????????????????????????????????????????????????if(vertical < pipeHeight + pipe['y']????????????????????????????????????????????????????????????????????????and abs(horizontal - pipe['x']) < game_images['pipeimage'][0].get_width()):????????????????????????????????????????????????????????????????????????return True????????????????????????????????????????????????????????????????????? |
#Output : pip install pygame | How to make Flappy Bird Game in Pygame?
# Checking if bird is above the sealevel.def isGameOver(horizontal, vertical, up_pipes, down_pipes):????????????????????????if vertical > elevation - 25 or vertical < 0:??????????????????????????????????????????????????????return True????????????????????????????????????# Checking if bird hits the upper pipe or not????????????????????????for pipe in up_pipes:????????????????????????????????????????????????????????????????????????pipeHeight = game_images['pipeimage'][0].get_height()????????????????????????????????????????????????if(vertical < pipeHeight + pipe['y']????????????????????????????????????????????????????????????????????????and abs(horizontal - pipe['x']) < game_images['pipeimage'][0].get_width()):????????????????????????????????????????????????????????????????????????return True?????????????????????????????????????????????????????????????????????
#Output : pip install pygame
[END] |
How to make Flappy Bird Game in Pygame? | https://www.geeksforgeeks.org/how-to-make-flappy-bird-game-in-pygame/ | def flappygame():
your_score = 0
horizontal = int(window_width / 5)
vertical = int(window_width / 2)
ground = 0
mytempheight = 100
# Generating two pipes for blitting on window
first_pipe = createPipe()
second_pipe = createPipe()
# List containing lower pipes
down_pipes = [
{"x": window_width + 300 - mytempheight, "y": first_pipe[1]["y"]},
{
"x": window_width + 300 - mytempheight + (window_width / 2),
"y": second_pipe[1]["y"],
},
]
# List Containing upper pipes
up_pipes = [
{"x": window_width + 300 - mytempheight, "y": first_pipe[0]["y"]},
{
"x": window_width + 200 - mytempheight + (window_width / 2),
"y": second_pipe[0]["y"],
},
]
pipeVelX = -4 # pipe velocity along x
bird_velocity_y = -9 # bird velocity
bird_Max_Vel_Y = 10
bird_Min_Vel_Y = -8
birdAccY = 1
# velocity while flapping
bird_flap_velocity = -8
# It is true only when the bird is flapping
bird_flapped = False
while True:
# Handling the key pressing events
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
if vertical > 0:
bird_velocity_y = bird_flap_velocity
bird_flapped = True
# This function will return true if the flappybird is crashed
game_over = isGameOver(horizontal, vertical, up_pipes, down_pipes)
if game_over:
return
# check for your_score
playerMidPos = horizontal + game_images["flappybird"].get_width() / 2
for pipe in up_pipes:
pipeMidPos = pipe["x"] + game_images["pipeimage"][0].get_width() / 2
if pipeMidPos <= playerMidPos < pipeMidPos + 4:
# Printing the score
your_score += 1
print(f"Your your_score is {your_score}")
if bird_velocity_y < bird_Max_Vel_Y and not bird_flapped:
bird_velocity_y += birdAccY
if bird_flapped:
bird_flapped = False
playerHeight = game_images["flappybird"].get_height()
vertical = vertical + min(bird_velocity_y, elevation - vertical - playerHeight)
# move pipes to the left
for upperPipe, lowerPipe in zip(up_pipes, down_pipes):
upperPipe["x"] += pipeVelX
lowerPipe["x"] += pipeVelX
# Add a new pipe when the first is about
# to cross the leftmost part of the screen
if 0 < up_pipes[0]["x"] < 5:
newpipe = createPipe()
up_pipes.append(newpipe[0])
down_pipes.append(newpipe[1])
# if the pipe is out of the screen, remove it
if up_pipes[0]["x"] < -game_images["pipeimage"][0].get_width():
up_pipes.pop(0)
down_pipes.pop(0)
# Lets blit our game images now
window.blit(game_images["background"], (0, 0))
for upperPipe, lowerPipe in zip(up_pipes, down_pipes):
window.blit(game_images["pipeimage"][0], (upperPipe["x"], upperPipe["y"]))
window.blit(game_images["pipeimage"][1], (lowerPipe["x"], lowerPipe["y"]))
window.blit(game_images["sea_level"], (ground, elevation))
window.blit(game_images["flappybird"], (horizontal, vertical))
# Fetching the digits of score.
numbers = [int(x) for x in list(str(your_score))]
width = 0
# finding the width of score images from numbers.
for num in numbers:
width += game_images["scoreimages"][num].get_width()
Xoffset = (window_width - width) / 1.1
# Blitting the images on the window.
for num in numbers:
window.blit(game_images["scoreimages"][num], (Xoffset, window_width * 0.02))
Xoffset += game_images["scoreimages"][num].get_width()
# Refreshing the game window and displaying the score.
pygame.display.update()
# Set the framepersecond
framepersecond_clock.tick(framepersecond) |
#Output : pip install pygame | How to make Flappy Bird Game in Pygame?
def flappygame():
your_score = 0
horizontal = int(window_width / 5)
vertical = int(window_width / 2)
ground = 0
mytempheight = 100
# Generating two pipes for blitting on window
first_pipe = createPipe()
second_pipe = createPipe()
# List containing lower pipes
down_pipes = [
{"x": window_width + 300 - mytempheight, "y": first_pipe[1]["y"]},
{
"x": window_width + 300 - mytempheight + (window_width / 2),
"y": second_pipe[1]["y"],
},
]
# List Containing upper pipes
up_pipes = [
{"x": window_width + 300 - mytempheight, "y": first_pipe[0]["y"]},
{
"x": window_width + 200 - mytempheight + (window_width / 2),
"y": second_pipe[0]["y"],
},
]
pipeVelX = -4 # pipe velocity along x
bird_velocity_y = -9 # bird velocity
bird_Max_Vel_Y = 10
bird_Min_Vel_Y = -8
birdAccY = 1
# velocity while flapping
bird_flap_velocity = -8
# It is true only when the bird is flapping
bird_flapped = False
while True:
# Handling the key pressing events
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
if vertical > 0:
bird_velocity_y = bird_flap_velocity
bird_flapped = True
# This function will return true if the flappybird is crashed
game_over = isGameOver(horizontal, vertical, up_pipes, down_pipes)
if game_over:
return
# check for your_score
playerMidPos = horizontal + game_images["flappybird"].get_width() / 2
for pipe in up_pipes:
pipeMidPos = pipe["x"] + game_images["pipeimage"][0].get_width() / 2
if pipeMidPos <= playerMidPos < pipeMidPos + 4:
# Printing the score
your_score += 1
print(f"Your your_score is {your_score}")
if bird_velocity_y < bird_Max_Vel_Y and not bird_flapped:
bird_velocity_y += birdAccY
if bird_flapped:
bird_flapped = False
playerHeight = game_images["flappybird"].get_height()
vertical = vertical + min(bird_velocity_y, elevation - vertical - playerHeight)
# move pipes to the left
for upperPipe, lowerPipe in zip(up_pipes, down_pipes):
upperPipe["x"] += pipeVelX
lowerPipe["x"] += pipeVelX
# Add a new pipe when the first is about
# to cross the leftmost part of the screen
if 0 < up_pipes[0]["x"] < 5:
newpipe = createPipe()
up_pipes.append(newpipe[0])
down_pipes.append(newpipe[1])
# if the pipe is out of the screen, remove it
if up_pipes[0]["x"] < -game_images["pipeimage"][0].get_width():
up_pipes.pop(0)
down_pipes.pop(0)
# Lets blit our game images now
window.blit(game_images["background"], (0, 0))
for upperPipe, lowerPipe in zip(up_pipes, down_pipes):
window.blit(game_images["pipeimage"][0], (upperPipe["x"], upperPipe["y"]))
window.blit(game_images["pipeimage"][1], (lowerPipe["x"], lowerPipe["y"]))
window.blit(game_images["sea_level"], (ground, elevation))
window.blit(game_images["flappybird"], (horizontal, vertical))
# Fetching the digits of score.
numbers = [int(x) for x in list(str(your_score))]
width = 0
# finding the width of score images from numbers.
for num in numbers:
width += game_images["scoreimages"][num].get_width()
Xoffset = (window_width - width) / 1.1
# Blitting the images on the window.
for num in numbers:
window.blit(game_images["scoreimages"][num], (Xoffset, window_width * 0.02))
Xoffset += game_images["scoreimages"][num].get_width()
# Refreshing the game window and displaying the score.
pygame.display.update()
# Set the framepersecond
framepersecond_clock.tick(framepersecond)
#Output : pip install pygame
[END] |
How to make Flappy Bird Game in Pygame? | https://www.geeksforgeeks.org/how-to-make-flappy-bird-game-in-pygame/ | # Import module
import random
import sys
import pygame
from pygame.locals import *
# All the Game Variables
window_width = 600
window_height = 499
# set height and width of window
window = pygame.display.set_mode((window_width, window_height))
elevation = window_height * 0.8
game_images = {}
framepersecond = 32
pipeimage = "images/pipe.png"
background_image = "images/background.jpg"
birdplayer_image = "images/bird.png"
sealevel_image = "images/base.jfif"
def flappygame():
your_score = 0
horizontal = int(window_width / 5)
vertical = int(window_width / 2)
ground = 0
mytempheight = 100
# Generating two pipes for blitting on window
first_pipe = createPipe()
second_pipe = createPipe()
# List containing lower pipes
down_pipes = [
{"x": window_width + 300 - mytempheight, "y": first_pipe[1]["y"]},
{
"x": window_width + 300 - mytempheight + (window_width / 2),
"y": second_pipe[1]["y"],
},
]
# List Containing upper pipes
up_pipes = [
{"x": window_width + 300 - mytempheight, "y": first_pipe[0]["y"]},
{
"x": window_width + 200 - mytempheight + (window_width / 2),
"y": second_pipe[0]["y"],
},
]
# pipe velocity along x
pipeVelX = -4
# bird velocity
bird_velocity_y = -9
bird_Max_Vel_Y = 10
bird_Min_Vel_Y = -8
birdAccY = 1
bird_flap_velocity = -8
bird_flapped = False
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
if vertical > 0:
bird_velocity_y = bird_flap_velocity
bird_flapped = True
# This function will return true
# if the flappybird is crashed
game_over = isGameOver(horizontal, vertical, up_pipes, down_pipes)
if game_over:
return
# check for your_score
playerMidPos = horizontal + game_images["flappybird"].get_width() / 2
for pipe in up_pipes:
pipeMidPos = pipe["x"] + game_images["pipeimage"][0].get_width() / 2
if pipeMidPos <= playerMidPos < pipeMidPos + 4:
your_score += 1
print(f"Your your_score is {your_score}")
if bird_velocity_y < bird_Max_Vel_Y and not bird_flapped:
bird_velocity_y += birdAccY
if bird_flapped:
bird_flapped = False
playerHeight = game_images["flappybird"].get_height()
vertical = vertical + min(bird_velocity_y, elevation - vertical - playerHeight)
# move pipes to the left
for upperPipe, lowerPipe in zip(up_pipes, down_pipes):
upperPipe["x"] += pipeVelX
lowerPipe["x"] += pipeVelX
# Add a new pipe when the first is
# about to cross the leftmost part of the screen
if 0 < up_pipes[0]["x"] < 5:
newpipe = createPipe()
up_pipes.append(newpipe[0])
down_pipes.append(newpipe[1])
# if the pipe is out of the screen, remove it
if up_pipes[0]["x"] < -game_images["pipeimage"][0].get_width():
up_pipes.pop(0)
down_pipes.pop(0)
# Lets blit our game images now
window.blit(game_images["background"], (0, 0))
for upperPipe, lowerPipe in zip(up_pipes, down_pipes):
window.blit(game_images["pipeimage"][0], (upperPipe["x"], upperPipe["y"]))
window.blit(game_images["pipeimage"][1], (lowerPipe["x"], lowerPipe["y"]))
window.blit(game_images["sea_level"], (ground, elevation))
window.blit(game_images["flappybird"], (horizontal, vertical))
# Fetching the digits of score.
numbers = [int(x) for x in list(str(your_score))]
width = 0
# finding the width of score images from numbers.
for num in numbers:
width += game_images["scoreimages"][num].get_width()
Xoffset = (window_width - width) / 1.1
# Blitting the images on the window.
for num in numbers:
window.blit(game_images["scoreimages"][num], (Xoffset, window_width * 0.02))
Xoffset += game_images["scoreimages"][num].get_width()
# Refreshing the game window and displaying the score.
pygame.display.update()
framepersecond_clock.tick(framepersecond)
def isGameOver(horizontal, vertical, up_pipes, down_pipes):
if vertical > elevation - 25 or vertical < 0:
return True
for pipe in up_pipes:
pipeHeight = game_images["pipeimage"][0].get_height()
if (
vertical < pipeHeight + pipe["y"]
and abs(horizontal - pipe["x"]) < game_images["pipeimage"][0].get_width()
):
return True
for pipe in down_pipes:
if (vertical + game_images["flappybird"].get_height() > pipe["y"]) and abs(
horizontal - pipe["x"]
) < game_images["pipeimage"][0].get_width():
return True
return False
def createPipe():
offset = window_height / 3
pipeHeight = game_images["pipeimage"][0].get_height()
y2 = offset + random.randrange(
0, int(window_height - game_images["sea_level"].get_height() - 1.2 * offset)
)
pipeX = window_width + 10
y1 = pipeHeight - y2 + offset
pipe = [
# upper Pipe
{"x": pipeX, "y": -y1},
# lower Pipe
{"x": pipeX, "y": y2},
]
return pipe
# program where the game starts
if __name__ == "__main__":
# For initializing modules of pygame library
pygame.init()
framepersecond_clock = pygame.time.Clock()
# Sets the title on top of game window
pygame.display.set_caption("Flappy Bird Game")
# Load all the images which we will use in the game
# images for displaying score
game_images["scoreimages"] = (
pygame.image.load("images/0.png").convert_alpha(),
pygame.image.load("images/1.png").convert_alpha(),
pygame.image.load("images/2.png").convert_alpha(),
pygame.image.load("images/3.png").convert_alpha(),
pygame.image.load("images/4.png").convert_alpha(),
pygame.image.load("images/5.png").convert_alpha(),
pygame.image.load("images/6.png").convert_alpha(),
pygame.image.load("images/7.png").convert_alpha(),
pygame.image.load("images/8.png").convert_alpha(),
pygame.image.load("images/9.png").convert_alpha(),
)
game_images["flappybird"] = pygame.image.load(birdplayer_image).convert_alpha()
game_images["sea_level"] = pygame.image.load(sealevel_image).convert_alpha()
game_images["background"] = pygame.image.load(background_image).convert_alpha()
game_images["pipeimage"] = (
pygame.transform.rotate(pygame.image.load(pipeimage).convert_alpha(), 180),
pygame.image.load(pipeimage).convert_alpha(),
)
print("WELCOME TO THE FLAPPY BIRD GAME")
print("Press space or enter to start the game")
# Here starts the main game
while True:
# sets the coordinates of flappy bird
horizontal = int(window_width / 5)
vertical = int((window_height - game_images["flappybird"].get_height()) / 2)
ground = 0
while True:
for event in pygame.event.get():
# if user clicks on cross button, close the game
if event.type == QUIT or (
event.type == KEYDOWN and event.key == K_ESCAPE
):
pygame.quit()
sys.exit()
# If the user presses space or
# up key, start the game for them
elif event.type == KEYDOWN and (
event.key == K_SPACE or event.key == K_UP
):
flappygame()
# if user doesn't press anykey Nothing happen
else:
window.blit(game_images["background"], (0, 0))
window.blit(game_images["flappybird"], (horizontal, vertical))
window.blit(game_images["sea_level"], (ground, elevation))
pygame.display.update()
framepersecond_clock.tick(framepersecond) |
#Output : pip install pygame | How to make Flappy Bird Game in Pygame?
# Import module
import random
import sys
import pygame
from pygame.locals import *
# All the Game Variables
window_width = 600
window_height = 499
# set height and width of window
window = pygame.display.set_mode((window_width, window_height))
elevation = window_height * 0.8
game_images = {}
framepersecond = 32
pipeimage = "images/pipe.png"
background_image = "images/background.jpg"
birdplayer_image = "images/bird.png"
sealevel_image = "images/base.jfif"
def flappygame():
your_score = 0
horizontal = int(window_width / 5)
vertical = int(window_width / 2)
ground = 0
mytempheight = 100
# Generating two pipes for blitting on window
first_pipe = createPipe()
second_pipe = createPipe()
# List containing lower pipes
down_pipes = [
{"x": window_width + 300 - mytempheight, "y": first_pipe[1]["y"]},
{
"x": window_width + 300 - mytempheight + (window_width / 2),
"y": second_pipe[1]["y"],
},
]
# List Containing upper pipes
up_pipes = [
{"x": window_width + 300 - mytempheight, "y": first_pipe[0]["y"]},
{
"x": window_width + 200 - mytempheight + (window_width / 2),
"y": second_pipe[0]["y"],
},
]
# pipe velocity along x
pipeVelX = -4
# bird velocity
bird_velocity_y = -9
bird_Max_Vel_Y = 10
bird_Min_Vel_Y = -8
birdAccY = 1
bird_flap_velocity = -8
bird_flapped = False
while True:
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
if vertical > 0:
bird_velocity_y = bird_flap_velocity
bird_flapped = True
# This function will return true
# if the flappybird is crashed
game_over = isGameOver(horizontal, vertical, up_pipes, down_pipes)
if game_over:
return
# check for your_score
playerMidPos = horizontal + game_images["flappybird"].get_width() / 2
for pipe in up_pipes:
pipeMidPos = pipe["x"] + game_images["pipeimage"][0].get_width() / 2
if pipeMidPos <= playerMidPos < pipeMidPos + 4:
your_score += 1
print(f"Your your_score is {your_score}")
if bird_velocity_y < bird_Max_Vel_Y and not bird_flapped:
bird_velocity_y += birdAccY
if bird_flapped:
bird_flapped = False
playerHeight = game_images["flappybird"].get_height()
vertical = vertical + min(bird_velocity_y, elevation - vertical - playerHeight)
# move pipes to the left
for upperPipe, lowerPipe in zip(up_pipes, down_pipes):
upperPipe["x"] += pipeVelX
lowerPipe["x"] += pipeVelX
# Add a new pipe when the first is
# about to cross the leftmost part of the screen
if 0 < up_pipes[0]["x"] < 5:
newpipe = createPipe()
up_pipes.append(newpipe[0])
down_pipes.append(newpipe[1])
# if the pipe is out of the screen, remove it
if up_pipes[0]["x"] < -game_images["pipeimage"][0].get_width():
up_pipes.pop(0)
down_pipes.pop(0)
# Lets blit our game images now
window.blit(game_images["background"], (0, 0))
for upperPipe, lowerPipe in zip(up_pipes, down_pipes):
window.blit(game_images["pipeimage"][0], (upperPipe["x"], upperPipe["y"]))
window.blit(game_images["pipeimage"][1], (lowerPipe["x"], lowerPipe["y"]))
window.blit(game_images["sea_level"], (ground, elevation))
window.blit(game_images["flappybird"], (horizontal, vertical))
# Fetching the digits of score.
numbers = [int(x) for x in list(str(your_score))]
width = 0
# finding the width of score images from numbers.
for num in numbers:
width += game_images["scoreimages"][num].get_width()
Xoffset = (window_width - width) / 1.1
# Blitting the images on the window.
for num in numbers:
window.blit(game_images["scoreimages"][num], (Xoffset, window_width * 0.02))
Xoffset += game_images["scoreimages"][num].get_width()
# Refreshing the game window and displaying the score.
pygame.display.update()
framepersecond_clock.tick(framepersecond)
def isGameOver(horizontal, vertical, up_pipes, down_pipes):
if vertical > elevation - 25 or vertical < 0:
return True
for pipe in up_pipes:
pipeHeight = game_images["pipeimage"][0].get_height()
if (
vertical < pipeHeight + pipe["y"]
and abs(horizontal - pipe["x"]) < game_images["pipeimage"][0].get_width()
):
return True
for pipe in down_pipes:
if (vertical + game_images["flappybird"].get_height() > pipe["y"]) and abs(
horizontal - pipe["x"]
) < game_images["pipeimage"][0].get_width():
return True
return False
def createPipe():
offset = window_height / 3
pipeHeight = game_images["pipeimage"][0].get_height()
y2 = offset + random.randrange(
0, int(window_height - game_images["sea_level"].get_height() - 1.2 * offset)
)
pipeX = window_width + 10
y1 = pipeHeight - y2 + offset
pipe = [
# upper Pipe
{"x": pipeX, "y": -y1},
# lower Pipe
{"x": pipeX, "y": y2},
]
return pipe
# program where the game starts
if __name__ == "__main__":
# For initializing modules of pygame library
pygame.init()
framepersecond_clock = pygame.time.Clock()
# Sets the title on top of game window
pygame.display.set_caption("Flappy Bird Game")
# Load all the images which we will use in the game
# images for displaying score
game_images["scoreimages"] = (
pygame.image.load("images/0.png").convert_alpha(),
pygame.image.load("images/1.png").convert_alpha(),
pygame.image.load("images/2.png").convert_alpha(),
pygame.image.load("images/3.png").convert_alpha(),
pygame.image.load("images/4.png").convert_alpha(),
pygame.image.load("images/5.png").convert_alpha(),
pygame.image.load("images/6.png").convert_alpha(),
pygame.image.load("images/7.png").convert_alpha(),
pygame.image.load("images/8.png").convert_alpha(),
pygame.image.load("images/9.png").convert_alpha(),
)
game_images["flappybird"] = pygame.image.load(birdplayer_image).convert_alpha()
game_images["sea_level"] = pygame.image.load(sealevel_image).convert_alpha()
game_images["background"] = pygame.image.load(background_image).convert_alpha()
game_images["pipeimage"] = (
pygame.transform.rotate(pygame.image.load(pipeimage).convert_alpha(), 180),
pygame.image.load(pipeimage).convert_alpha(),
)
print("WELCOME TO THE FLAPPY BIRD GAME")
print("Press space or enter to start the game")
# Here starts the main game
while True:
# sets the coordinates of flappy bird
horizontal = int(window_width / 5)
vertical = int((window_height - game_images["flappybird"].get_height()) / 2)
ground = 0
while True:
for event in pygame.event.get():
# if user clicks on cross button, close the game
if event.type == QUIT or (
event.type == KEYDOWN and event.key == K_ESCAPE
):
pygame.quit()
sys.exit()
# If the user presses space or
# up key, start the game for them
elif event.type == KEYDOWN and (
event.key == K_SPACE or event.key == K_UP
):
flappygame()
# if user doesn't press anykey Nothing happen
else:
window.blit(game_images["background"], (0, 0))
window.blit(game_images["flappybird"], (horizontal, vertical))
window.blit(game_images["sea_level"], (ground, elevation))
pygame.display.update()
framepersecond_clock.tick(framepersecond)
#Output : pip install pygame
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | def signup():
print(
"Please enter the username by which you \
wanna access your account"
)
username = input("please enter here: ")
password = input("Enter a password: ") |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
def signup():
print(
"Please enter the username by which you \
wanna access your account"
)
username = input("please enter here: ")
password = input("Enter a password: ")
#Output : 2021-06-01 14:44:02.851506
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | # pssd means password, ussnm is username
def user_information(ussnm, pssd):
name = input("enter your name please: ")
address = input("your address")
age = input("Your age please")
ussnm_ = ussnm + " task.txt"
f = open(ussnm_, "a")
f.write(pssd)
f.write("\nName: ")
f.write(name)
f.write("\n")
f.write("Address :")
f.write(address)
f.write("\n")
f.write("Age :")
f.write(age)
f.write("\n")
f.close()
def signup():
print(
"Please enter the username by which you\
wanna access your account"
)
username = input("please enter here: ")
password = input("Enter a password: ")
user_information(username, password) |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
# pssd means password, ussnm is username
def user_information(ussnm, pssd):
name = input("enter your name please: ")
address = input("your address")
age = input("Your age please")
ussnm_ = ussnm + " task.txt"
f = open(ussnm_, "a")
f.write(pssd)
f.write("\nName: ")
f.write(name)
f.write("\n")
f.write("Address :")
f.write(address)
f.write("\n")
f.write("Age :")
f.write(age)
f.write("\n")
f.close()
def signup():
print(
"Please enter the username by which you\
wanna access your account"
)
username = input("please enter here: ")
password = input("Enter a password: ")
user_information(username, password)
#Output : 2021-06-01 14:44:02.851506
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | def login():
print("Please enter your username ")
user_nm = input("Enter here: ")
# Password as entered while logging in
pssd_wr = (input("enterr the password")) + "\n"
try:
usernm = user_nm + " task.txt"
f_ = open(usernm, "r")
# variable 'k' contains the password as saved
# in the file
k = f_.readlines(0)[0]
f_.close()
# Checking if the Password entered is same as
# the password saved while signing in
if pssd_wr == k:
print(
"1--to view your data \n2--To add task \n3--Update\
task status \n4--View task status"
)
a = input()
else:
print("SIR YOUR PASSWORD OR USERNAME IS WRONG , Plz enter Again")
login()
except Exception as e:
print(e)
login() |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
def login():
print("Please enter your username ")
user_nm = input("Enter here: ")
# Password as entered while logging in
pssd_wr = (input("enterr the password")) + "\n"
try:
usernm = user_nm + " task.txt"
f_ = open(usernm, "r")
# variable 'k' contains the password as saved
# in the file
k = f_.readlines(0)[0]
f_.close()
# Checking if the Password entered is same as
# the password saved while signing in
if pssd_wr == k:
print(
"1--to view your data \n2--To add task \n3--Update\
task status \n4--View task status"
)
a = input()
else:
print("SIR YOUR PASSWORD OR USERNAME IS WRONG , Plz enter Again")
login()
except Exception as e:
print(e)
login()
#Output : 2021-06-01 14:44:02.851506
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | def signup():
print("Please enter the username by which you wanna access your account")
username = input("please enter here: ")
password = input("Enter a password: ")
user_information(username, password)
print("Sir please proceed towards log in")
login() |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
def signup():
print("Please enter the username by which you wanna access your account")
username = input("please enter here: ")
password = input("Enter a password: ")
user_information(username, password)
print("Sir please proceed towards log in")
login()
#Output : 2021-06-01 14:44:02.851506
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | def login():
print("Please enter your username ")
user_nm = input("Enter here: ")
# Password as entered while logging in
pssd_wr = (input("enterr the password")) + "\n"
try:
usernm = user_nm + " task.txt"
f_ = open(usernm, "r")
# variable 'k' contains the password as
# saved in the file
k = f_.readlines(0)[0]
f_.close()
# Checking if the Password entered is same
# as the password saved while signing in
if pssd_wr == k:
print(
"1--to view your data \n2--To add task \n3--Update\
task \n4--VIEW TASK STATUS"
)
a = input()
if a == "1":
view_data(usernm)
elif a == "2":
# add task
task_information(usernm)
elif a == "3":
task_update(user_nm)
elif a == "4":
task_update_viewer(user_nm)
else:
print("Wrong input ! ")
else:
print("SIR YOUR PASSWORD OR USERNAME IS WRONG")
login()
except Exception as e:
print(e)
login()
def view_data(username):
pass
def task_information(username):
pass
def task_update(username):
pass
def task_update_viewer(username):
pass |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
def login():
print("Please enter your username ")
user_nm = input("Enter here: ")
# Password as entered while logging in
pssd_wr = (input("enterr the password")) + "\n"
try:
usernm = user_nm + " task.txt"
f_ = open(usernm, "r")
# variable 'k' contains the password as
# saved in the file
k = f_.readlines(0)[0]
f_.close()
# Checking if the Password entered is same
# as the password saved while signing in
if pssd_wr == k:
print(
"1--to view your data \n2--To add task \n3--Update\
task \n4--VIEW TASK STATUS"
)
a = input()
if a == "1":
view_data(usernm)
elif a == "2":
# add task
task_information(usernm)
elif a == "3":
task_update(user_nm)
elif a == "4":
task_update_viewer(user_nm)
else:
print("Wrong input ! ")
else:
print("SIR YOUR PASSWORD OR USERNAME IS WRONG")
login()
except Exception as e:
print(e)
login()
def view_data(username):
pass
def task_information(username):
pass
def task_update(username):
pass
def task_update_viewer(username):
pass
#Output : 2021-06-01 14:44:02.851506
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | def view_data(username):
ff = open(username, "r")
print(ff.read())
ff.close() |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
def view_data(username):
ff = open(username, "r")
print(ff.read())
ff.close()
#Output : 2021-06-01 14:44:02.851506
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | def task_information(username):
print("Sir enter n.o of task you want to ADD")
j = int(input())
f1 = open(username, "a")
for i in range(1, j + 1):
task = input("enter the task")
target = input("enter the target")
pp = "TASK " + str(i) + " :"
qq = "TARGET " + str(i) + " :"
f1.write(pp)
f1.write(task)
f1.write("\n")
f1.write(qq)
f1.write(target)
f1.write("\n")
print("Do u want to stop press space bar otherwise enter")
s = input()
if s == " ":
break
f1.close() |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
def task_information(username):
print("Sir enter n.o of task you want to ADD")
j = int(input())
f1 = open(username, "a")
for i in range(1, j + 1):
task = input("enter the task")
target = input("enter the target")
pp = "TASK " + str(i) + " :"
qq = "TARGET " + str(i) + " :"
f1.write(pp)
f1.write(task)
f1.write("\n")
f1.write(qq)
f1.write(target)
f1.write("\n")
print("Do u want to stop press space bar otherwise enter")
s = input()
if s == " ":
break
f1.close()
#Output : 2021-06-01 14:44:02.851506
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | def task_update(username):
username = username + " TASK.txt"
print("Please enter the tasks which are completed ")
task_completed = input()
print("Enter task which are still not started by you")
task_not_started = input()
print("Enter task which you are doing")
task_ongoing = input()
fw = open(username, "a")
DT = str(datetime.datetime.now())
fw.write(DT)
fw.write("\n")
fw.write("COMPLETED TASK \n")
fw.write(task_completed)
fw.write("\n")
fw.write("ONGOING TASK \n")
fw.write(task_ongoing)
fw.write("\n")
fw.write("NOT YET STARTED\n")
fw.write(task_not_started)
fw.write("\n") |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
def task_update(username):
username = username + " TASK.txt"
print("Please enter the tasks which are completed ")
task_completed = input()
print("Enter task which are still not started by you")
task_not_started = input()
print("Enter task which you are doing")
task_ongoing = input()
fw = open(username, "a")
DT = str(datetime.datetime.now())
fw.write(DT)
fw.write("\n")
fw.write("COMPLETED TASK \n")
fw.write(task_completed)
fw.write("\n")
fw.write("ONGOING TASK \n")
fw.write(task_ongoing)
fw.write("\n")
fw.write("NOT YET STARTED\n")
fw.write(task_not_started)
fw.write("\n")
#Output : 2021-06-01 14:44:02.851506
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | def task_update_viewer(username):
ussnm = username + " TASK.txt"
o = open(ussnm, "r")
print(o.read())
o.close() |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
def task_update_viewer(username):
ussnm = username + " TASK.txt"
o = open(ussnm, "r")
print(o.read())
o.close()
#Output : 2021-06-01 14:44:02.851506
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | if __name__ == "__main__":
print("WELCOME TO ANURAG`S TASK MANAGER")
print("sir are you new to this software")
a = int(input("Type 1 if new otherwise press 0 ::"))
if a == 1:
signup()
elif a == 0:
login()
else:
print("You have provided wrong input !") |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
if __name__ == "__main__":
print("WELCOME TO ANURAG`S TASK MANAGER")
print("sir are you new to this software")
a = int(input("Type 1 if new otherwise press 0 ::"))
if a == 1:
signup()
elif a == 0:
login()
else:
print("You have provided wrong input !")
#Output : 2021-06-01 14:44:02.851506
[END] |
Personalized Task Manager in Python | https://www.geeksforgeeks.org/personalized-task-manager-in-python/ | import datetime
# pssd means password, ussnm is username
def user_information(ussnm, pssd):
name = input("enter your name please: ")
address = input("your address")
age = input("Your age please")
ussnm_ = ussnm + " task.txt"
f = open(ussnm_, "a")
f.write(pssd)
f.write("\nName: ")
f.write(name)
f.write("\n")
f.write("Address :")
f.write(address)
f.write("\n")
f.write("Age :")
f.write(age)
f.write("\n")
f.close()
def signup():
print("Please enter the username by which you wanna access your account")
username = input("please enter here: ")
password = input("Enter a password: ")
user_information(username, password)
print("Sir please proceed towards log in")
login()
def login():
print("Please enter your username ")
user_nm = input("Enter here: ")
# Password as entered while logging in
pssd_wr = (input("enterr the password")) + "\n"
try:
usernm = user_nm + " task.txt"
f_ = open(usernm, "r")
# variable 'k' contains the password as saved
# in the file
k = f_.readlines(0)[0]
f_.close()
# Checking if the Password entered is same as
# the password saved while signing in
if pssd_wr == k:
print(
"1--to view your data \n2--To add task \n3--Update\
task \n4--VIEW TASK STATUS"
)
a = input()
if a == "1":
view_data(usernm)
elif a == "2":
# add task
task_information(usernm)
elif a == "3":
task_update(user_nm)
elif a == "4":
task_update_viewer(user_nm)
else:
print("Wrong input ! bhai dekh kr input dal")
else:
print("SIR YOUR PASSWORD OR USERNAME IS WRONG")
login()
except Exception as e:
print(e)
login()
def view_data(username):
ff = open(username, "r")
print(ff.read())
ff.close()
def task_information(username):
print("Sir enter n.o of task you want to ADD")
j = int(input())
f1 = open(username, "a")
for i in range(1, j + 1):
task = input("enter the task")
target = input("enter the target")
pp = "TASK " + str(i) + " :"
qq = "TARGET " + str(i) + " :"
f1.write(pp)
f1.write(task)
f1.write("\n")
f1.write(qq)
f1.write(target)
f1.write("\n")
print("Do u want to stop press space bar otherwise enter")
s = input()
if s == " ":
break
f1.close()
def task_update(username):
username = username + " TASK.txt"
print("Please enter the tasks which are completed ")
task_completed = input()
print("Enter task which are still not started by you")
task_not_started = input()
print("Enter task which you are doing")
task_ongoing = input()
fw = open(username, "a")
DT = str(datetime.datetime.now())
fw.write(DT)
fw.write("\n")
fw.write("COMPLETED TASK \n")
fw.write(task_completed)
fw.write("\n")
fw.write("ONGOING TASK \n")
fw.write(task_ongoing)
fw.write("\n")
fw.write("NOT YET STARTED\n")
fw.write(task_not_started)
fw.write("\n")
def task_update_viewer(username):
ussnm = username + " TASK.txt"
o = open(ussnm, "r")
print(o.read())
o.close()
if __name__ == "__main__":
print("WELCOME TO ANURAG`S TASK MANAGER")
print("sir are you new to this software")
a = int(input("Type 1 if new otherwise press 0 ::"))
if a == 1:
signup()
elif a == 0:
login()
else:
print("You have provided wrong input !") |
#Output : 2021-06-01 14:44:02.851506 | Personalized Task Manager in Python
import datetime
# pssd means password, ussnm is username
def user_information(ussnm, pssd):
name = input("enter your name please: ")
address = input("your address")
age = input("Your age please")
ussnm_ = ussnm + " task.txt"
f = open(ussnm_, "a")
f.write(pssd)
f.write("\nName: ")
f.write(name)
f.write("\n")
f.write("Address :")
f.write(address)
f.write("\n")
f.write("Age :")
f.write(age)
f.write("\n")
f.close()
def signup():
print("Please enter the username by which you wanna access your account")
username = input("please enter here: ")
password = input("Enter a password: ")
user_information(username, password)
print("Sir please proceed towards log in")
login()
def login():
print("Please enter your username ")
user_nm = input("Enter here: ")
# Password as entered while logging in
pssd_wr = (input("enterr the password")) + "\n"
try:
usernm = user_nm + " task.txt"
f_ = open(usernm, "r")
# variable 'k' contains the password as saved
# in the file
k = f_.readlines(0)[0]
f_.close()
# Checking if the Password entered is same as
# the password saved while signing in
if pssd_wr == k:
print(
"1--to view your data \n2--To add task \n3--Update\
task \n4--VIEW TASK STATUS"
)
a = input()
if a == "1":
view_data(usernm)
elif a == "2":
# add task
task_information(usernm)
elif a == "3":
task_update(user_nm)
elif a == "4":
task_update_viewer(user_nm)
else:
print("Wrong input ! bhai dekh kr input dal")
else:
print("SIR YOUR PASSWORD OR USERNAME IS WRONG")
login()
except Exception as e:
print(e)
login()
def view_data(username):
ff = open(username, "r")
print(ff.read())
ff.close()
def task_information(username):
print("Sir enter n.o of task you want to ADD")
j = int(input())
f1 = open(username, "a")
for i in range(1, j + 1):
task = input("enter the task")
target = input("enter the target")
pp = "TASK " + str(i) + " :"
qq = "TARGET " + str(i) + " :"
f1.write(pp)
f1.write(task)
f1.write("\n")
f1.write(qq)
f1.write(target)
f1.write("\n")
print("Do u want to stop press space bar otherwise enter")
s = input()
if s == " ":
break
f1.close()
def task_update(username):
username = username + " TASK.txt"
print("Please enter the tasks which are completed ")
task_completed = input()
print("Enter task which are still not started by you")
task_not_started = input()
print("Enter task which you are doing")
task_ongoing = input()
fw = open(username, "a")
DT = str(datetime.datetime.now())
fw.write(DT)
fw.write("\n")
fw.write("COMPLETED TASK \n")
fw.write(task_completed)
fw.write("\n")
fw.write("ONGOING TASK \n")
fw.write(task_ongoing)
fw.write("\n")
fw.write("NOT YET STARTED\n")
fw.write(task_not_started)
fw.write("\n")
def task_update_viewer(username):
ussnm = username + " TASK.txt"
o = open(ussnm, "r")
print(o.read())
o.close()
if __name__ == "__main__":
print("WELCOME TO ANURAG`S TASK MANAGER")
print("sir are you new to this software")
a = int(input("Type 1 if new otherwise press 0 ::"))
if a == 1:
signup()
elif a == 0:
login()
else:
print("You have provided wrong input !")
#Output : 2021-06-01 14:44:02.851506
[END] |
Download Instagram profile pic using Python | https://www.geeksforgeeks.org/download-instagram-profile-pic-using-python/ | import requests
from bs4 import BeautifulSoup as bs
import json
import random
import os.path |
#Output : pip install requests | Download Instagram profile pic using Python
import requests
from bs4 import BeautifulSoup as bs
import json
import random
import os.path
#Output : pip install requests
[END] |
Download Instagram profile pic using Python | https://www.geeksforgeeks.org/download-instagram-profile-pic-using-python/ | insta_url = "https://www.instagram.com"
inta_username = input("enter username of instagram : ")
response = requests.get(f"{insta_url}/{inta_username}/") |
#Output : pip install requests | Download Instagram profile pic using Python
insta_url = "https://www.instagram.com"
inta_username = input("enter username of instagram : ")
response = requests.get(f"{insta_url}/{inta_username}/")
#Output : pip install requests
[END] |
Download Instagram profile pic using Python | https://www.geeksforgeeks.org/download-instagram-profile-pic-using-python/ | if response.ok:
html = response.text
bs_html = bs(html, features="lxml")
bs_html = bs_html.text
index = bs_html.find("profile_pic_url_hd") + 21
remaining_text = bs_html[index:]
remaining_text_index = remaining_text.find("requested_by_viewer") - 3
string_url = remaining_text[:remaining_text_index].replace("\\u0026", "&")
print(string_url, "\n \n downloading..........") |
#Output : pip install requests | Download Instagram profile pic using Python
if response.ok:
html = response.text
bs_html = bs(html, features="lxml")
bs_html = bs_html.text
index = bs_html.find("profile_pic_url_hd") + 21
remaining_text = bs_html[index:]
remaining_text_index = remaining_text.find("requested_by_viewer") - 3
string_url = remaining_text[:remaining_text_index].replace("\\u0026", "&")
print(string_url, "\n \n downloading..........")
#Output : pip install requests
[END] |
Download Instagram profile pic using Python | https://www.geeksforgeeks.org/download-instagram-profile-pic-using-python/ | while True:
filename = "pic" + str(random.randint(1, 100000)) + ".jpg"
file_exists = os.path.isfile(filename)
if not file_exists:
with open(filename, "wb+") as handle:
response = requests.get(string_url, stream=True)
if not response.ok:
print(response)
for block in response.iter_content(1024):
if not block:
break
handle.write(block)
else:
continue
break
print("\n downloading completed ..............") |
#Output : pip install requests | Download Instagram profile pic using Python
while True:
filename = "pic" + str(random.randint(1, 100000)) + ".jpg"
file_exists = os.path.isfile(filename)
if not file_exists:
with open(filename, "wb+") as handle:
response = requests.get(string_url, stream=True)
if not response.ok:
print(response)
for block in response.iter_content(1024):
if not block:
break
handle.write(block)
else:
continue
break
print("\n downloading completed ..............")
#Output : pip install requests
[END] |
Download Instagram profile pic using Python | https://www.geeksforgeeks.org/download-instagram-profile-pic-using-python/ | import instaloader
ig = instaloader.Instaloader()
dp = input("Enter Insta username : ")
ig.download_profile(dp, profile_pic_only=True) |
#Output : pip install requests | Download Instagram profile pic using Python
import instaloader
ig = instaloader.Instaloader()
dp = input("Enter Insta username : ")
ig.download_profile(dp, profile_pic_only=True)
#Output : pip install requests
[END] |