简体   繁体   中英

Export a File (CSV, PDF) From Django Admin Form Inputs

All within the Django admin , I'd like to enter form fields related to generating a report. Fields you'd expect in a report: report name, report type, start and end dates, report fields, etc.

How would one take these inputs, grab the inputs from the request, pass these inputs to an API (in the background), then process it (in queue-like fashion), finally create a CSV or PDF to download?

I'm fine with creating the admin model form and I think grabbing the inputs when the form is submitted in the admin, then I think I simply pass those inputs to my other API code to process...

My questions are:

  1. When the third-party API is processing the request, is there a special way to handle this lag time?
  2. Where and how would I return the result - which is a CSV or PDF - in the admin interface? The /change/ page?

Is there best-practice for this? I haven't been able to find an example of this when dealing with the admin. I'm not new to Python but am somewhat new to Django.

Nobody will likely answer. Therefore, I'll share my high-level general solution.

  1. You'll need to setup celery.py and modify your __init__.py like it shows in celery's documentation. The key "gotcha" is where they put "proj", you should put the actual name of your project, not "proj".
  2. In your admin.ModelAdmin class, override save_model(self, request, obj, form, change) to capture the form data submitted from the admin form.
  3. Use the form inputs and pass to a celery task function in tasks.py within the current app. Ex: get_report.delay(name, start, end, type) . Note the .delay part as this is what allows it to run in the background without having to wait at the screen after you submit the form.
  4. In save_model(...) , you still have to call super().save_model(request, obj, form, change) at the end.
  5. The most important step of all - you have open two terminals! 1 for running python manage.py runserver (for example) and another for starting the celery worker. I'm on Windows and Windows has issues so a non-concurrent solution is celery -A scorecard worker --pool=solo -l info (to start the worker - you type this in Terminal), OR, you can install eventlet and use eventlet as the --pool=eventlet value instead of --pool=solo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM