I have designed a PDF button in the blogs.html file to download a PDF file that has been uploaded from the admin panel. It does not work. I have coded models.py, admin.py, and urls.py in the blogs app, as well as the blogs.html file. Need for improvement?
model.py
class Blog(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=150, blank=True, unique=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
featured_image = models.ImageField(upload_to='uploads/%y/%m/%d')
short_description = CKEditor5Field('short description', config_name='extends')
blog_body = CKEditor5Field('blog body', config_name='extends')
pdf_file = models.FileField(upload_to='pdfs/', blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
,,,
admin.py
class BlogAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
list_display = ('title', 'category', 'auther', 'pdf_file', 'status', 'is_featured',)
admin.site.register(Category)
admin.site.register(Blog, BlogAdmin)
views.py
def download_blog_pdf_by_id(request, blog_id):
"""Handle PDF download using blog ID"""
blog = get_object_or_404(Blog, id=blog_id)
if not blog.pdf_file:
raise Http404("No PDF available for this blog post")
file_path = blog.pdf_file.path
if os.path.exists(file_path):
with open(file_path, 'rb') as pdf:
response = HttpResponse(pdf.read(), content_type='application/pdf')
filename = f"{blog.title.replace(' ', '_')}.pdf"
response['Content-Disposition'] = f'attachment; filename="{filename}"'
return response
else:
raise Http404("PDF file not found")
urls.py
urlpatterns = [
path('<int:category_id>/', views.posts_by_category, name='posts_by_category'),
path('blog/download/<int:blog_id>/', views.download_blog_pdf_by_id, name='download_blog_pdf_by_id'),
]
blogs.html
<!-- download pdf -->
{% if pdf_file_exists %}
<a href="/download/pdf/{{ pdf_id }}/" class="btn btn-success">
<i class="bi bi-file-earmark-pdf me-2"></i>Download PDF
</a>
{% else %}
<button class="btn btn-secondary" disabled>
<i class="bi bi-file-earmark-x me-2"></i>PDF Not Available
</button>
{% endif %}
The link to the page containing the PDF file download button is the PDF download button