from django.conf import settings from django.contrib import staticfiles from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound from django.shortcuts import get_object_or_404 from django.views.generic import ListView import requests import weasyprint from membershipworks.models import Member from .models import Certification WIKI_URL = settings.WIKI_URL class MemberCertificationListView(ListView): template_name = "paperwork/member_certifications.dj.html" context_object_name = "certifications" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["show_outdated"] = ( self.request.GET.get("show_outdated", "false").lower() == "true" ) return context def get_queryset(self): self.member = get_object_or_404(Member, uid=self.kwargs["uid"]) return Certification.objects.filter(member=self.member) def certification_pdf(request, cert_name): wiki_page = f"{cert_name.replace('_', ' ')} Certification" r = requests.get( WIKI_URL + "/api.php", params={ "action": "askargs", "conditions": wiki_page, "printouts": "Version|Approval Date|Approval status", "format": "json", "api_version": "2", "origin": "*", }, ) results = r.json()["query"]["results"] if wiki_page not in results: return HttpResponseNotFound( f'No such certification found on wiki: {wiki_page}' ) printouts = results[wiki_page]["printouts"] if printouts["Approval status"] != ["approve"]: return HttpResponseBadRequest( f'Certification is not yet approved on wiki: {wiki_page}' ) filename = ( f'{wiki_page}_v{printouts["Version"][0]} - {printouts["Approval Date"][0]}.pdf' ) html = weasyprint.HTML(f"{WIKI_URL}/index.php?title={wiki_page}") stylesheet = staticfiles.finders.find("paperwork/certification-print.css") pdf = html.write_pdf(stylesheets=[stylesheet]) return HttpResponse( pdf, headers={ "Content-Type": "application/pdf", "Content-Disposition": f'inline; filename="{filename}"', }, )