0

I am automatically generating a Word doc when a user enters a number into the front-end website. My starting goal was to have Django initiate a download of the doc, but that has been unsuccessful.

Now, I just want to save the file to the server and deliver the file location URL back to my JS so I can create a link for the user to click.

The front-end uses a AJAX call to pass the user-input back to the view. The trouble is with getting the path correct inside the Django view. Here's my view:

@login_required
@custom_header
def create_document(request, *args, **kwargs):
    """Create a doc and return URI."""

I tried using this SO method:

    doc_path = static('doc.docx')

^ That returns this error: IOError: [Errno 2] No such file or directory: '/static/doc.docx'

I manually created the folders and doc.docx file, in both locations, so they do exist. As suggested on SO here, I changed it to this:

    doc_path = os.path.join(os.path.dirname(__file__), 'doc/doc.docx')

^ But that results in: IOError: [Errno 13] Permission denied: './app_folder/doc/doc.docx'

Rest of the View:

    doc_name = doc.docx

    # Template on which the doc is based
    template_path = os.path.join(os.path.dirname(__file__), 'doc/template.docx')

    form = CleanerForm(request.POST)
    if form.is_valid():
        user_input = form.cleaned_data.get('user_input')
        doc_context = requests.get(
            'https://MY_API_URI/user_input=%s' % user_input,
        )
    else:
        # Failure Actions

    # Generate doc with context
    print os.getcwd()
    template = DocxTemplate(tmpl_path)
    template.render(json.loads(doc_context.text))
    template.save(doc_path)

    return HttpResponse(doc_path)

Imports

from docxtpl import DocxTemplate
import json
import os
from .forms import CleanerForm
from django.http import HttpResponse
from django.templatetags.static import static

My initial code (which doesn't work) to open the file was:

with open(doc_path) as this_doc:
    wrapper = File(this_doc)
    content_type = mimetypes.guess_type(doc_path)[0]
    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Length'] = os.path.getsize(doc_path)
    response['Content-Disposition'] = "attachment; filename=%s" % doc_name
Community
  • 1
  • 1
whyeliah
  • 95
  • 1
  • 2
  • 9
  • I'm surprised you cannot automatically download your word file because I do it with pdfs. Have you tried something like: `response = HttpResponse(mydata, mimetype='application/vnd.ms-word')` `response['Content-Disposition'] = 'attachment; filename=example.doc'` `return response` – HenryM Aug 19 '16 at 19:08
  • And here's a link that should help with the static file url http://stackoverflow.com/questions/11721818/django-get-the-static-files-url-in-view – HenryM Aug 19 '16 at 19:10

0 Answers0