admin.py
# myapp/admin.py
from django.utils.timezone import now
from .models import UserProfile, UserReviews
from django.utils import timezone
from .models import Internship, Batch, AddTask, UserInternships, TaskSubmission
from docx import Document
from .Card.GenerateCard import write_text, write_qr
import zipfile
import pandas as pd
import os
from django.conf import settings
from django.http import HttpResponse
from django.contrib import admin, messages
import qrcode
from .models import UserInternships
from PIL import Image
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import pypandoc
import docx2pdf
@admin.register(Internship)
class InternshipAdmin(admin.ModelAdmin):
list_display = ('internship_id', 'domain', 'name', 'is_active')
search_fields = ('name', 'domain')
list_filter = ('is_active',)
@admin.register(Batch)
class BatchAdmin(admin.ModelAdmin):
list_display = ('internship', 'start_date', 'batch_date', 'is_active')
search_fields = ('internship__name',)
list_filter = ('start_date', 'batch_date', 'is_active')
def save_model(self, request, obj, form, change):
today = timezone.now().date()
if obj.start_date < today or obj.batch_date < today:
obj.is_active = False
else:
obj.is_active = True
super().save_model(request, obj, form, change)
def replace_placeholders(template_path, output_path, replacements):
doc = Document(template_path)
for paragraph in doc.paragraphs:
for key, value in replacements.items():
if key in paragraph.text:
paragraph.text = paragraph.text.replace(key, value)
doc.save(output_path)
def generate_offer_letter(modeladmin, request, queryset):
# Use STATICFILES_DIRS to get the correct path to the template
template_path = os.path.join(settings.STATICFILES_DIRS[0], 'templates', 'offer_letter_template.docx')
if not os.path.exists(template_path):
modeladmin.message_user(request, "Template file does not exist.", level='error')
return
output_dir = os.path.join(settings.MEDIA_ROOT, 'offer_letters')
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for user_internship in queryset:
replacements = {
'{name}': user_internship.full_name,
'{email}': user_internship.email,
'{internship_domain}': user_internship.internship.domain,
'{current_date}': now().strftime('%d/%m/%Y'),
'{date}': user_internship.batch.start_date.strftime('%d/%m/%Y')
}
output_filename = f'offer_letter_{user_internship.user.username}_{user_internship.id}.docx'
output_path = os.path.join(output_dir, output_filename)
replace_placeholders(template_path, output_path, replacements)
user_internship.offer_letter = f'offer_letters/{output_filename}'
user_internship.is_active = True # Set is_active to True
user_internship.save()
modeladmin.message_user(request, "Offer letters generated successfully.")
generate_offer_letter.short_description = "Generate offer letters"
def generate_certificates(modeladmin, request, queryset):
template_path = "/home/nptechcrafters/projectconnecsys/static/templates/certificatedemo.png"
if not os.path.exists(template_path):
modeladmin.message_user(request, "Template file does not exist.", level=messages.ERROR)
return
output_dir = os.path.join(settings.MEDIA_ROOT, 'certificates')
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for obj in queryset:
try:
if obj.full_name and not pd.isna(obj.full_name):
# Generate QR code
qr_url = f'https://nptechcrafters.pythonanywhere.com/certificate/{obj.pk}'
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(qr_url)
qr.make(fit=True)
qr_img = qr.make_image(fill_color="black", back_color="white")
# Save QR code image
qr_code_directory = os.path.join(settings.MEDIA_ROOT, 'QR')
os.makedirs(qr_code_directory, exist_ok=True)
img_path = os.path.join(qr_code_directory, f"{obj.full_name}.png")
qr_img.save(img_path)
# Write text and QR code on the certificate template
try:
# Ensure write_text and write_qr functions are correctly implemented
write_text(obj.full_name, obj.internship.domain, obj.batch.batch_date, obj.pk, template_path)
write_qr(img_path, obj.full_name)
# Convert the image to PDF
certificate_image_path = os.path.join(output_dir, f"{obj.full_name}_certificate.png")
pdf_path = certificate_image_path.replace(".png", ".pdf")
with Image.open(certificate_image_path) as img:
img.convert('RGB').save(pdf_path)
# Update the model with the certificate path
obj.certificate = f'certificates/{os.path.basename(pdf_path)}'
obj.save()
except Exception as e:
modeladmin.message_user(request, f"Error found while writing on the template: {e}", level=messages.ERROR)
else:
modeladmin.message_user(request, f"Skipping invalid user {obj.full_name}!", level=messages.ERROR)
except Exception as e:
modeladmin.message_user(request, f"Error generating certificate for {obj.full_name}: {str(e)}", level=messages.ERROR)
modeladmin.message_user(request, "Certificates generated successfully.", level=messages.SUCCESS)
generate_certificates.short_description = "Generate Certificates"
@admin.register(UserInternships)
class UserInternshipsAdmin(admin.ModelAdmin):
list_display = ('user', 'internship', 'is_active', 'batch', 'full_name', 'email', 'start_date', 'batch_date',
'current_date', 'is_completed', 'offer_letter', 'certificate')
search_fields = ('user__username', 'internship__name', 'name', 'email', 'is_active')
list_filter = ('internship', 'batch', 'is_active')
actions = [generate_certificates, generate_offer_letter]
@admin.register(AddTask)
class AddTaskAdmin(admin.ModelAdmin):
list_display = ('internship', 'batch', 'task_title', 'start_date', 'end_date', 'is_active')
list_filter = ('internship', 'batch', 'is_active')
@admin.register(TaskSubmission)
class TaskSubmissionAdmin(admin.ModelAdmin):
list_display = [
'user', 'internship', 'batch', 'github_repo_link', 'linkedin_post_link',
'is_approved', 'description', 'status', 'submission_date',
'issue_raised', 'rating', 'issue'
]
list_filter = ['status', 'is_approved', 'issue_raised']
search_fields = ['user__username', 'internship__name', 'batch__batch_date']
@admin.register(UserReviews)
class UserReviewsAdmin(admin.ModelAdmin):
list_display = ('user', 'internship', 'review', 'is_active')
search_fields = ('user__username', 'internship__internship__name')
list_filter = ('is_active', 'internship')
admin.site.register(UserProfile)
Comments
Post a Comment