resolution-archive/resulation/views.py

354 lines
14 KiB
Python
Raw Permalink Normal View History

2025-01-30 17:27:48 +06:00
from django.shortcuts import render, HttpResponse, get_object_or_404, Http404, redirect
2025-01-26 11:22:57 +06:00
from .models import resulation
2025-01-30 13:07:48 +06:00
from datetime import datetime
import os, uuid
import misdghs.settings
2025-01-30 17:27:48 +06:00
from django.http import FileResponse, StreamingHttpResponse
from urllib.parse import unquote
from misdghs import settings
from django.core.files.storage import default_storage
2025-02-24 12:33:09 +06:00
from django.shortcuts import render, redirect
from django.urls import reverse_lazy, reverse
from django.contrib.auth.views import LoginView
from django.contrib.auth.models import User
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic.edit import CreateView
from .models import Verification
from .forms import SignupForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
class SignupView(SuccessMessageMixin, CreateView):
form_class = SignupForm
template_name = 'registration/signup.html'
success_url = reverse_lazy('login')
success_message = "Registration successful! Please verify your email."
def form_valid(self, form):
print("=== Checking form validity in SignupView ===")
# Check if the username already exists
existing_username = User.objects.filter(username=form.cleaned_data['username'])
if existing_username.exists():
print(f"Username '{form.cleaned_data['username']}' already exists.")
form.add_error('username', 'Username already taken.')
return super().form_invalid(form)
# Check if the email already exists
existing_email = User.objects.filter(email=form.cleaned_data['email'])
if existing_email.exists():
print(f"Email '{form.cleaned_data['email']}' already registered.")
form.add_error('email', 'Email already registered.')
return super().form_invalid(form)
# Form is valid, proceed to create user
print("Form validation passed. Proceeding to create user...")
response = super().form_valid(form)
print(f"User created successfully. User object: {self.object}")
# Verify that self.object exists and has the correct fields
if self.object:
print(f"New user details - Username: {self.object.username}, Email: {self.object.email}")
print("Proceeding to send verification email.")
self.send_verification_email()
else:
print("Error: User object is not created after form submission.")
return response
def send_verification_email(self):
print("\n=== Entering send_verification_email method ===")
try:
# Create a new Verification instance
verification = Verification.objects.create(user=self.object)
print(f"Verification object created with key: {verification.key}")
# Generate the verification key (you can improve this by using a more secure method)
import uuid
key = str(uuid.uuid4())
print(f"Generated verification key: {key}")
# Prepare email content
subject = 'Verify your email'
body = (
f'Please verify your account by clicking this link: '
f'{self.request.build_absolute_uri(reverse("verify", kwargs={"key": key}))}'
)
html_body = (
f'<a href="{self.request.build_absolute_uri(reverse("verify", kwargs={"key": key}))}">'
'Verify Email</a>'
)
# Send email using Django's send_mail function
print(f"Attempting to send verification email to: {self.object.email}")
from django.core.mail import send_mail
send_mail(
subject,
body,
'dpmehealth@gmail.com',
[self.object.email],
fail_silently=False
)
print("Verification email sent successfully.")
except Exception as e:
print(f"Error sending verification email: {str(e)}")
raise # Re-raise the exception to see it in logs or handle appropriately
def generate_key(self):
import uuid
return str(uuid.uuid4())
def Verify(request, key):
try:
print(f"\n=== Verification view called with key: {key} ===")
verification = Verification.objects.get(key=key)
if not verification.verified:
print(f"Verification found and unverified. Proceeding to verify.")
verification.verified = True
verification.save()
user = verification.user
print(f"User associated with this verification: {user.username}")
user.is_active = True
user.save()
messages.success(request, 'Email verified successfully!')
return redirect('login')
else:
print("Verification link already used.")
messages.error(request, 'Already verified.')
except Verification.DoesNotExist:
print(f"Invalid verification key: {key}")
messages.error(request, 'Invalid verification link.')
return redirect('home')
def signin(request):
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, "You have successfully logged in!")
return redirect("home")
messages.error(request, "Invalid username or password.")
else:
return render(request, "registration/signin.html")
@login_required
def signout(request):
logout(request)
messages.info(request, "You have successfully logged out.")
return redirect("home")
2025-01-26 11:22:57 +06:00
# Create your views here.
def Home(request):
return render(request,'resulation/home.html')
2025-02-24 12:33:09 +06:00
@login_required
2025-01-30 13:07:48 +06:00
def Savepdf(request):
if request.method == 'POST':
2025-01-26 11:22:57 +06:00
try:
2025-01-30 13:07:48 +06:00
# Get text form fields
pdftype= request.POST.get('pdftype')
2025-01-26 11:22:57 +06:00
org_unit = request.POST.get('org_unit')
topic = request.POST.get('topic')
tittle = request.POST.get('tittle')
m_number = request.POST.get('m_number')
m_date = request.POST.get('m_date')
m_venue = request.POST.get('m_venue')
2025-01-30 13:07:48 +06:00
# Get file uploads
2025-01-26 11:22:57 +06:00
attendance_file = request.FILES.get('attendance_file')
res_con_mou_file = request.FILES.get('res_con_mou_file')
2025-01-30 13:07:48 +06:00
# Create a new seminar instance with text fields
if attendance_file:
2025-01-30 17:27:48 +06:00
new_filename1 = f"attendance_{uuid.uuid4()}.pdf"
path1 = os.path.join('media', 'attendance_files', new_filename1)
2025-01-30 13:07:48 +06:00
with open(path1, 'wb') as destination:
for chunk in attendance_file.chunks():
destination.write(chunk)
if res_con_mou_file:
2025-01-30 17:27:48 +06:00
new_filename2 = f"res_con_{uuid.uuid4()}.pdf"
path2 = os.path.join('media', 'resolution_files', new_filename2)
2025-01-30 13:07:48 +06:00
print(path2)
with open(path2, 'wb') as destination:
for chunk in res_con_mou_file.chunks():
destination.write(chunk)
seminar = resulation(
pdftype=pdftype,
2025-01-26 11:22:57 +06:00
org_unit=org_unit,
topic=topic,
tittle=tittle,
m_number=m_number,
m_date=m_date,
m_venue=m_venue,
2025-01-30 17:27:48 +06:00
attendance_file=new_filename1,
res_con_mou_file=new_filename2,
2025-01-30 13:07:48 +06:00
)
seminar.save()
print(path1)
2025-01-26 11:22:57 +06:00
message = "Data Inserted successfully"
2025-01-30 13:07:48 +06:00
# Redirect after a successful save
2025-01-26 11:22:57 +06:00
return render(request, "resulation/home.html", {'message': message})
2025-01-30 13:07:48 +06:00
2025-01-26 11:22:57 +06:00
except Exception as e:
2025-01-30 13:07:48 +06:00
# Handle any errors (e.g., invalid file types or sizes)
print(f"Error processing form: {str(e)}")
return render(request, 'resulation/resulation.html', {'error': str(e)})
else:
# Render the form template
2025-01-26 11:22:57 +06:00
return render(request, 'resulation/resulation.html')
2025-02-24 12:33:09 +06:00
@login_required
2025-01-30 17:27:48 +06:00
def Viewresulation(request):
2025-01-26 11:22:57 +06:00
# Get all records from database
2025-02-18 17:21:42 +06:00
pdf_records = resulation.objects.filter(pdftype='Meeting Minutes').order_by('-m_date') # Latest first
2025-01-30 17:27:48 +06:00
return render(request, 'resulation/viewresulation.html', {'pdf_records': pdf_records})
2025-01-30 13:07:48 +06:00
2025-02-24 12:33:09 +06:00
@login_required
2025-02-02 12:26:20 +06:00
def file_download(request, type, filename):
2025-01-30 17:27:48 +06:00
# Construct the full path to the file
2025-02-02 12:26:20 +06:00
if type== 'attendance':
file_path = os.path.join(settings.MEDIA_ROOT, 'attendance_files', filename)
if type=='resolution':
file_path = os.path.join(settings.MEDIA_ROOT, 'resolution_files', filename)
2025-01-30 13:07:48 +06:00
2025-01-30 17:27:48 +06:00
# Use sendfile to stream the file directly
return FileResponse(open(file_path, 'rb'), content_type='application/pdf')
2025-01-30 13:07:48 +06:00
2025-01-26 11:22:57 +06:00
2025-02-24 12:33:09 +06:00
@login_required
2025-01-26 11:22:57 +06:00
def Mou(request):
2025-02-18 16:23:22 +06:00
if request.method == 'POST':
try:
# Get text form fields
pdftype= request.POST.get('pdftype')
first_party = request.POST.get('first_party')
second_party = request.POST.get('second_party')
contract_mou_date = request.POST.get('contract_mou_date')
# Get file uploads
res_con_mou_file = request.FILES.get('res_con_mou_file')
if res_con_mou_file:
new_filename2 = f"res_con_{uuid.uuid4()}.pdf"
path2 = os.path.join('media', 'resolution_files', new_filename2)
print(path2)
with open(path2, 'wb') as destination:
for chunk in res_con_mou_file.chunks():
destination.write(chunk)
seminar = resulation(
pdftype=pdftype,
first_party = first_party,
second_party = second_party,
contract_mou_date = contract_mou_date,
res_con_mou_file=new_filename2,
)
seminar.save()
message = "Data Inserted successfully"
# Redirect after a successful save
return render(request, "resulation/home.html", {'message': message})
except Exception as e:
# Handle any errors (e.g., invalid file types or sizes)
print(f"Error processing form: {str(e)}")
return render(request, 'resulation/mou.html', {'error': str(e)})
else:
# Render the form template
return render(request, 'resulation/mou.html')
2025-02-24 12:33:09 +06:00
@login_required
2025-02-18 16:23:22 +06:00
def Viewmou(request):
# Get all records from database
2025-02-18 17:21:42 +06:00
pdf_records = resulation.objects.filter(pdftype='MoU').order_by('-m_date') # Latest first
print(pdf_records)
2025-02-18 16:23:22 +06:00
return render(request, 'resulation/viewmou.html', {'pdf_records': pdf_records})
2025-02-24 12:33:09 +06:00
@login_required
2025-02-18 16:23:22 +06:00
def Contract(request):
if request.method == 'POST':
try:
# Get text form fields
pdftype= request.POST.get('pdftype')
contract_name= request.POST.get('topic')
first_party = request.POST.get('first_party')
second_party = request.POST.get('second_party')
contract_mou_date = request.POST.get('contract_mou_date')
contract_mou_closing_date = request.POST.get('closing_date')
duration= request.POST.get('duration')
# Get file uploads
res_con_mou_file = request.FILES.get('res_con_mou_file')
if res_con_mou_file:
new_filename2 = f"res_con_{uuid.uuid4()}.pdf"
path2 = os.path.join('media', 'resolution_files', new_filename2)
print(path2)
with open(path2, 'wb') as destination:
for chunk in res_con_mou_file.chunks():
destination.write(chunk)
seminar = resulation(
pdftype=pdftype,
topic=contract_name,
first_party = first_party,
second_party = second_party,
contract_mou_date = contract_mou_date,
closing_date= contract_mou_closing_date,
duration=duration,
res_con_mou_file=new_filename2,
)
seminar.save()
message = "Data Inserted successfully"
# Redirect after a successful save
return render(request, "resulation/home.html", {'message': message})
except Exception as e:
# Handle any errors (e.g., invalid file types or sizes)
print(f"Error processing form: {str(e)}")
return render(request, 'resulation/contract.html', {'error': str(e)})
else:
# Render the form template
return render(request, 'resulation/contract.html')
2025-02-24 12:33:09 +06:00
@login_required
2025-02-18 16:23:22 +06:00
def Viewcontract(request):
# Get all records from database
2025-02-18 17:21:42 +06:00
pdf_records = resulation.objects.filter(pdftype='Contract').order_by('-m_date') # Latest first
2025-02-27 15:58:42 +06:00
return render(request, 'resulation/viewcontract.html', {'pdf_records': pdf_records})
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def contracts_list(request):
records = resulation.objects.all() # Replace with your model
paginator = Paginator(records, 10) # Show 10 records per page
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
pdf_records = paginator.page(page)
except PageNotAnInteger:
pdf_records = paginator.page(1)
except EmptyPage:
pdf_records = paginator.page(paginator.num_pages)
return {'pdf_records': pdf_records, 'paginator': paginator}