Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wagtail document links downloading instead of displaying as a page

Tags:

django

wagtail

It seems that the default configuration for Wagtail CMS is to have links to documents trigger an automatic download of the document instead of displaying the document in the browser. Is there a simple way to change this configuration?

like image 931
David B Avatar asked Dec 24 '22 12:12

David B


1 Answers

Following on from LB's accepted answer above, the following code will allow you to serve up a document to be viewed without relying on Google Document Viewer.

You can also revert to standard behaviour by passing a querystring parameter e.g. https://.../?download=True

from django.http import HttpResponse
from wagtail.core import hooks


@hooks.register('before_serve_document')
def serve_pdf(document, request):
    if document.file_extension != 'pdf':
        return  # Empty return results in the existing response
    response = HttpResponse(document.file.read(), content_type='application/pdf')
    response['Content-Disposition'] = 'filename="' + document.file.name.split('/')[-1] + '"'
    if request.GET.get('download', False) in [True, 'True', 'true']:
        response['Content-Disposition'] = 'attachment; ' + response['Content-Disposition']
    return response
like image 182
richardk Avatar answered Apr 29 '23 16:04

richardk