Wagtail document links downloading instead of displaying as a page

Viewed 2151

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?

4 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

Another approach to this could be to hook into the before_serve_document wagtail hook.

https://docs.wagtail.io/en/v2.9.3/reference/hooks.html?highlight=document%20serving#document-serving

You could customize the response based on the document this way, here is a pretty rough example that shows how the hook works.

You still need to resolve how to generate a viewable URL that shows the file though.

from wagtail.wagtailcore import hooks
from django.shortcuts import redirect


@hooks.register('before_serve_document')
def serve_document(document, request):
    # eg. use document.file_extension, document.url, document.filename
    if document.file_extension == 'pdf':
        google_view_pdf_base = 'https://docs.google.com/viewer?url='
        # document.url is a relative URL so more work needed here
        # also URL should probably be URL encoded
        redirect_url = google_view_pdf_base + document.url
        # must return an instance of HTTPResponse
        return redirect(redirect_url)
    # no return means the normal page serve will operate

In html file where your are displaying your pdf just add file before url:

For example: {{ file_name.file.url }}

Related