0

I have a celery task that runs periodically and fetches some data for all companies that use a certain accounting service. I now need to make that task run on-demand with a click of a button, and fetch only the current company's data.

Modified celery task:

@APP.task
def import_data_for_company(company_id):
    for integration in settings.INTEGRATIONS:
        if integration["owner"]["company_id"] == company_id:
            print("omlette du fromage")

Current button in Django template

{% for integration in settings.INTEGRATIONS %}
    {% if company.company_id == integration.owner.company_id %}
        <div class="button">
        <a class="btn" href="#">Import Data</a>
        </div>
    {% endif %}
{% endfor %}

I need to trigger that task from the Django template and pass a company ID as an argument while doing it. But according to this comment, I cannot pass arguments from the Django template. Writing a custom template tag/filter seems not to help here.

What are my options for calling that function via this button?

Have to note, that I'm very green at this still.

perrer
  • 29
  • 5
  • Why you use same loop in template and celery task it seems redundant – Ahtisham Jan 04 '22 at 17:22
  • Yeah, it doesn't look good. The INTEGRATIONS is a list of dictionaries, so I have to loop through them, to 1) get the correct company's specs (task) and 2) check if the current company is listed in the INTEGRATIONS, and only then show the button. Do you have a better suggestion for this? – perrer Jan 04 '22 at 20:31

1 Answers1

1

You should create a view that takes your company id. Within this view, you will trigger import_data_for_company. Then you can redirect back to your initial view. Or you can trigger the view with AJAX as well. Add the URL in your template accordingly: {% url 'some_name' company.company_id %}

urls.py:

path(
    "your_desired_trigger_url/<id:company_id>/",
    trigger_company_data,
    name="some_name",
),

views.py:

def trigger_company_data(request, company_id):
    import_data_for_company(company_id)
    return HttpResponseRedirect(reverse("your_initial_view"))
Marco
  • 2,371
  • 2
  • 12
  • 19