| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- # textdocs/views.py
- from django.shortcuts import render, get_object_or_404, redirect
- from django.http import HttpResponse
- from django.template.loader import render_to_string
- from weasyprint import HTML
- from .models import Document
- from .forms import DocumentForm
- def document_list(request):
- """Shows a list of all created documents."""
- documents = Document.objects.order_by('-created_at')
- return render(request, 'textdocs/document_list.html', {'documents': documents})
- def document_detail(request, pk):
- """Shows the details of a single document."""
- document = get_object_or_404(Document, pk=pk)
- return render(request, 'textdocs/document_detail.html', {'document': document})
- def document_create(request):
- """Handles the creation of a new document via a form."""
- if request.method == 'POST':
- form = DocumentForm(request.POST)
- if form.is_valid():
- document = form.save()
- return redirect('document_detail', pk=document.pk)
- else:
- form = DocumentForm()
- return render(request, 'textdocs/document_form.html', {'form': form})
- def generate_pdf(request, pk):
- """Generates a PDF for a specific document."""
- document = get_object_or_404(Document, pk=pk)
- # Render the HTML template with the document context
- html_string = render_to_string('textdocs/document_pdf.html', {'document': document})
- # Use WeasyPrint to create the PDF
- html = HTML(string=html_string, base_url=request.build_absolute_uri())
- pdf = html.write_pdf()
- # Create an HTTP response with the PDF
- response = HttpResponse(pdf, content_type='application/pdf')
- response['Content-Disposition'] = f'attachment; filename="{document.title}.pdf"'
- return response
|