# textdocs/views.py from django.shortcuts import render, get_object_or_404, redirect from django.urls import reverse_lazy # NEW: Useful for delete success URL 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}) # --- NEW: View for updating a document --- def document_update(request, pk): """Handles editing and saving an existing document.""" document = get_object_or_404(Document, pk=pk) if request.method == 'POST': # Pass the instance to the form to update it form = DocumentForm(request.POST, instance=document) if form.is_valid(): form.save() return redirect('document_detail', pk=document.pk) else: # Pre-populate the form with the existing document's data form = DocumentForm(instance=document) return render(request, 'textdocs/document_form.html', {'form': form}) # --- NEW: View for deleting a document --- def document_delete(request, pk): """Handles the deletion of a document after confirmation.""" document = get_object_or_404(Document, pk=pk) if request.method == 'POST': # This is after the user confirms the deletion document.delete() return redirect('document_list') # Redirect to the list after deletion # If it's a GET request, show the confirmation page return render(request, 'textdocs/document_confirm_delete.html', {'document': document}) def generate_pdf(request, pk): """Generates a PDF for a specific document.""" document = get_object_or_404(Document, pk=pk) html_string = render_to_string('textdocs/document_pdf.html', {'document': document}) html = HTML(string=html_string, base_url=request.build_absolute_uri()) pdf = html.write_pdf() response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = f'attachment; filename="{document.title}.pdf"' return response