title: Continuously check if file exists with AJAX in Django
body: <p>I've developed an application in Django where a user goes to a form on a site and enters in an Elasticsearch query, then generating a report for the user to download. It all works fine and dandy, but lately in testing some more queries we've noticed that some return a lot of results which leads to a timeout request. </p>
  
  <p>What we've figured out that we'd like to do is have Django continuously check if a file exists (because it won't be written to the local system until it's completed) to prevent that timeout issue. Additionally, once the file is done being created we want to add a download button so that the user knows it is done. </p>
  
  <p>Following <a href="https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html" rel="nofollow noreferrer">this</a> tutorial, I added a function to my views.py and associated it with a url which is then called by a javascript code block in my html form. Because I am brand new to using AJAX, JQuery, Javascript, and Django I'm not quite sure how to get it to work. Mainly, I'm trying to figure out how to get it to keep checking if the file is done being created yet. If this were just using basic Python I would do a while loop but I'm unclear how to translate that to JavaScript. </p>
  
  <p><strong>views.py</strong></p>
  
  <pre><code>def check_progress(request):
      """
      Returns whether document generation is complete or in progress
      Returns 0 for in-progress, 1 for complete (either due to completion, or error)
      """
      # check if file exists, return response as a JSON
      file = "/report.docx"
      data = {
          "file_created": path.exists(file)
      }
      return JsonResponse(data)
  </code></pre>
  
  <p><strong>urls.py</strong></p>
  
  <pre><code>from django.urls import path
  from . import views
  from django.conf import settings
  from django.conf.urls.static import static
  
  urlpatterns = [
      path('', views.get_query, name='form'),
      path('^ajax/check_progress/$', views.check_progress, name='check_progress')
  ]  + static(settings.STATIC_URL, document_root=settings.STAT)
  </code></pre>
  
  <p><strong>form.html</strong></p>
  
  <pre><code>{% block javascript %}
    &lt;script&gt;
      $("#id_username").change(function () {
        var username = $(this).val();
  
        $.ajax({
          url: '/ajax/check_progress/',
          type: 'HEAD',
          data: {
            'file_exists': 'True'
          },
          dataType: 'json',
          success: function (data) {
            if (data.exists) {
              alert("This file is not yet created");
            }
          }
        });
  
      });
    &lt;/script&gt;
  {% endblock %}
  </code></pre>