Using Django and Celery to retrieve a file that was generated in the background

Operating on a page called foo.com/process, you have the capability to generate data reports. At times, when dealing with substantial amounts of data, the generation process can be time-consuming. To address this, a Celery task was implemented to manage the PDF generation aspect. Reports are initiated by clicking on a PDF image:

<i data-processid="{{process.id}}" data-filename="{{process.pdf}}" class="fas fa-file-download getPdf"></i>

Upon clicking the FA icon, an AJAX POST request is triggered towards the Django view:

$(".getPdf").on('click', function(event) {

    var thisId = $(this).data('processid');
    var filename = $(this).data('filename');

    $.post({
        url: "{% url 'process' %}", // Refers to foo.com/process
        data: {
            csrfmiddlewaretoken: "{{ csrf_token }}",
            id: thisId
        },
        success: function(data) {
            ... handle success
        },
        error: function(data) {
            ... handle error
        },
        traditional: true
    }).done();

    downloadPdf(filename);

    function downloadPdf(filename) {
        setTimeout(function() { window.location.href = filename; }, 10000);

    };
});

The AJAX operation forwards the request to the backend to commence the Celery process for generating the PDF, followed by immediate execution of a downloadPfd function - a delayed process assumed to facilitate file downloading via JavaScript. The timeout allocated gives allowance for the file completion.

Despite creating and positioning the PDF in the principal project directory (with intentions to later adjust), a "file not found" issue arises.

Considering alternatives, utilizing Django might offer a more viable solution, which I've explored as well.

Concerning the POST segment of my Django view, here's what it contains:

class ProcessView(generic.DetailView):
    template_name = 'pages/process.html'

    def get(self, request):
        # Handling GET operations
        return render(request, self.template_name, {'process_form': process_form, 'process': process_list})

    def post(self, request):
            # Obtain Process ID from incoming request
            process_id = request.POST.get('id')

            # Extract necessary objects and execute queries
            ... python and DB processes ...

            # Triggers a Celery task for asynchronous PDF generation
            task = create_pdf.delay(sensor, range_period)

            return HttpResponseRedirect(self.request.path_info, {"task_id": task.task_id })

The POST functionality functions proficiently. Upon button click, an AJAX POST initiates, leading to the creation of a Celery task that generates a file. However, acquiring the task_id at the frontend poses a challenge.

The complexity arises when attempting to utilize the Celery task.task_id on the frontend to intermittently monitor my Django view for PDF completion status and eventually downloading the relevant file. Equipped with both the filename and task ID, navigating this process remains intricate.

Attempting to follow guidance from a concise tutorial, implementing the script component proves challenging due to limited expertise in JS. Struggling with understanding the section related to "Checking periodically for file existence and initiating download," mainly due to the disparity between function-based views in the tutorial and my reliance on class-based views within my project.

Answer №1

Your query seems to have some missing components, but I'll address the first one for now:

  1. To extract the task_id from an ajax post, your view should send back a JsonResponse:

return JsonResponse({
    'task_id': task_id
})
  1. In your javascript ajax success function, you need to retrieve the task_id from the response usually returned in the success block.

  2. Afterwards, your javascript code should continuously check a separate django view that can fetch the output of the celery task (probably the PDF filename) in order to provide the filename of the generated PDF.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Laravel Ajax document ready function

In my Laravel code, I have two functions that I am trying to call but I haven't been able to find a solution online. Please review the following; Ajax Code: <script> $(document).ready(function(){ $(function(){ var $datasearch=$('#d ...

What causes the content of my container to disappear following a setInterval div swap in Internet Explorer?

While developing a website on Chrome and Firefox, I was informed that it also needs to function properly in Internet Explorer. I managed to resolve the double padding issue in IE, but now I'm facing a new problem. The content of my "grid" disappears a ...

JavaScript payload object's name

Here is the data I have received. {name: "Sinto 6", val: {…}, line: "Sinto 6"} line: "Sinto 6" name: "Sinto 6" val: AvgMachTime: 253 AvgManTime: 1343 CollectMachTimer: 359 CollectManTimer: 108 CycleTimeMach: 359 Cy ...

Alter the font color of text using JavaScript in an HTML document

I am struggling to change the title color in my HTML code below, but the text color does not seem to be changing. How can I make this adjustment? /** * Generate a HTML table with the provided data */ Highcharts.Chart.prototype.generateTable ...

What is the best way to combine django rest-framework with angularjs?

I have been searching for a solution to this seemingly simple issue, but I can't seem to find it anywhere. I have test data stored in my database and I'm trying to figure out how to use Angular to display this data from my Django Rest Framework A ...

Incorporate a jQuery/JS module within an Angular component

I wanted to incorporate a jQuery function that utilizes an external library within my component, so I included its library in angular.json "scripts": [ "node_modules/jquery/dist/jquery.min.js", "node_modules/popper ...

The issue persists with setState not functioning correctly and the checkboxes for filtering not registering as checked

I am currently in the process of developing a simple ecommerce platform which focuses on shoe shopping. Users will be able to search for shoes and apply filters based on brand and type. Here's where I stand with my progress: Clicking on filter check ...

What is the reason behind div elements shifting when hovering over a particular element?

Currently, I have floated all my div elements (icons) to the left and margin-lefted them to create space in between. I've displayed them inline as well. However, when I hover over one element (icon), the rest of the elements move. Can you please help ...

Retrieve information from a Django model in mysql based on user input

I am trying to retrieve data from a Django model (stored in MySQL) based on user input. Essentially, I have an HTML search bar where users can enter a value, which should then fetch related data from the Django model and display it on another HTML page. ...

Using curly braces for imports within a Nuxt component

I am facing an issue with importing Three.js in a Nuxt component. <script> import * as THREE from "three"; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' .. Although the first line of code works fine, t ...

Retrieve the value of EJS depending on the JavaScript variable

I am in the process of developing a website for booking appointments using Express, EJS, and MongoDB. When a request is made to '/booking', the book page appears displaying all details about the doctor. Upon clicking the book button next to each ...

developing a dynamic structure that can store multiple levels of data

I am grappling with the task of creating a multidimensional array in JavaScript to send data via an Ajax call to PHP. My expertise in JS is limited, especially when it comes to this particular task... I have shared the code on JSFiddle The desired struct ...

Transform a nested array of objects into a distinct set of objects based on the data in JavaScript or TypeScript

I have a unique situation where I am dealing with a double nested array of objects, and I need to restructure it into a specific array format to better align with my table structure. Here are the current objects I'm working with and the desired resul ...

When using Ajax/PHP, the .post and .load methods do not yield any data in return

I've been working on an AJAX login/logout form, and while the login process is smooth, I'm encountering some issues with the "logout" functionality. Here's the Javascript code: $("#logout").live("click", function(){ $.post("/hd/ajax.php" ...

Maximizing PUT Methods in HTTP RESTful Services

I've been playing around with my routes file and I'm looking to switch up the method being called (delete instead of update). Code Snippets: # User management API GET /users @controllers.Users.findUsers POST /user ...

Access a file from an npm module using an executable command

I have a npm module called @jcubic/lips, which includes an executable file. I need to open a file located within the module's directory. This module is installed globally. The specific file I want to access is ../examples/helpers.lips, relative to th ...

Accessing new data added with ForeignKey in Django Admin Area

Let's consider a scenario where we have the following models: # models.py from django.db import models class Category(models.Model): title = models.CharField(max_length=60) class CategoryDescription(models.Model) category = models.Foreign ...

Pros and Cons of Using HTML5 Mode versus Hash Mode in AngularJS

When using AngularJS 1.3, it is necessary to include the <base> tag in HTML5 mode. This led me to consider the pros and cons of HTML5 mode versus Hash mode. In Hash mode, the major drawback is that URLs can appear unattractive and may not be easy fo ...

Monitoring Disqus comments within the Django Admin interface

Integrating Disqus comments with Django can be done using django-disqus, but currently there does not seem to be a way to handle comment moderation directly within Django or Django Admin. Moderation needs to be done through the Disqus dashboard. Is anyone ...

What could be causing the React variable to malfunction within my state object?

class ColoredSquares extends React.Component { constructor() { super(); this.selectedColor = 'green'; } state = { backgroundColor: this.selectedColor, width: "50px", height: "50p ...