views.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # textdocs/views.py
  2. from django.shortcuts import render, get_object_or_404, redirect
  3. from django.http import HttpResponse
  4. from django.template.loader import render_to_string
  5. from weasyprint import HTML
  6. from .models import Document
  7. from .forms import DocumentForm
  8. def document_list(request):
  9. """Shows a list of all created documents."""
  10. documents = Document.objects.order_by('-created_at')
  11. return render(request, 'textdocs/document_list.html', {'documents': documents})
  12. def document_detail(request, pk):
  13. """Shows the details of a single document."""
  14. document = get_object_or_404(Document, pk=pk)
  15. return render(request, 'textdocs/document_detail.html', {'document': document})
  16. def document_create(request):
  17. """Handles the creation of a new document via a form."""
  18. if request.method == 'POST':
  19. form = DocumentForm(request.POST)
  20. if form.is_valid():
  21. document = form.save()
  22. return redirect('document_detail', pk=document.pk)
  23. else:
  24. form = DocumentForm()
  25. return render(request, 'textdocs/document_form.html', {'form': form})
  26. def generate_pdf(request, pk):
  27. """Generates a PDF for a specific document."""
  28. document = get_object_or_404(Document, pk=pk)
  29. # Render the HTML template with the document context
  30. html_string = render_to_string('textdocs/document_pdf.html', {'document': document})
  31. # Use WeasyPrint to create the PDF
  32. html = HTML(string=html_string, base_url=request.build_absolute_uri())
  33. pdf = html.write_pdf()
  34. # Create an HTTP response with the PDF
  35. response = HttpResponse(pdf, content_type='application/pdf')
  36. response['Content-Disposition'] = f'attachment; filename="{document.title}.pdf"'
  37. return response