title: How use python-docx to stream a file from template
body: <p>Ok so right now I have a function in my django app that creates a word document like so: </p>
  
  <pre><code>def form_view(request):
  
      if request.method == 'POST':
         #do a bunch of things
         context = { 
          'model_1' : model_1,
          }
          in_template = "Forms/mytemplate.docx"
  
          doc = DocxTemplate(in_template)
          doc.render(context)
          out_filename = "outfile.docx"
          http_word_response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
          http_word_response['Content-Disposition'] = 'attachment; filename=%s' % out_filename
          doc.save(http_word_response)
          return http_word_response
  
       else:
         return render( request, 'mysite/form.html', context)
  </code></pre>
  
  <p>So right now, the file is served up as the <code>http_word_response</code> variable and it works great</p>
  
  <p>I want to change this so that the file is actually created and saved into S3, but I'd like to not save the file locally first and just use the stream function of the python-docx package: <a href="https://python-docx.readthedocs.io/en/latest/user/documents.html#opening-a-file-like-document" rel="nofollow noreferrer">https://python-docx.readthedocs.io/en/latest/user/documents.html#opening-a-file-like-document</a></p>
  
  <p>Here's the sample it gives:</p>
  
  <pre><code>with open('foobar.docx', 'rb') as f:
      source_stream = StringIO(f.read())
  document = Document(source_stream)
  source_stream.close()
  ...
  target_stream = StringIO()
  document.save(target_stream)
  </code></pre>
  
  <p>I'm not sure how to translate that sample into reading in my template file and outputting a file/object I can then send to S3 and do something with. </p>
  
  <p>My best guess would start like this:</p>
  
  <pre><code>        with open(in_template, 'rb') as f:
              source_stream = StringIO(f.read())
          doc = DocxTemplate(source_stream)
          source_stream.close()
  
          target_stream = StringIO()
          document.save(target_stream)
  </code></pre>
  
  <p>But then I get confused on where my <code>doc.render(context)</code> part goes and how I can change the name of the <code>target_stream</code> to a filename I want.</p>
  
  <p>Any help on getting started with that is appreciated.</p>