[Django]-Polling celery task and return on display

8👍

You can use Django-celery-results. It is an easy and nice extension of celery that enable you to store your tasks results in django database.
install the extension using :

$ pip install -U django-celery-results

update settings.py :

CELERY_RESULT_BACKEND = 'django-db'

INSTALLED_APP = (
    ...
    ...
    django_celery_results
)

Create the Celery database tables by performing a database migrations:

$ python manage.py migrate django_celery_results

Then you can get the list of finished tasks from the database and display it in your view.

from django_celery_results.models import TaskResult
def tasks_view(request):
    tasks = TaskResult.objects.all()
    template = "tasks.html" 
    return render(request, template, {'tasks': tasks})

Define the template “templates/tasks.html”

 <html>
    <head>
        <title>tasks</title>
    </head>
    <body>
    {% if tasks %}
    <ul>
    {% for task in tasks %}
        <li> {{task.id}} : {{ task.result }}</a></li>
    {% endfor %}
    </ul>
    <p>It works!</p>
   {% else %}
    <p>No tasks are available.</p>
   {% endif %}

    </body>
</html>

Leave a comment