Categories
Python Answers

How to cancel an already executing task with Celery and Python?

Sometimes, we want to cancel an already executing task with Celery and Python.

In this article, we’ll look at how to cancel an already executing task with Celery and Python.

How to cancel an already executing task with Celery and Python?

To cancel an already executing task with Celery and Python, we can use the revoke function.

For instance, we write

from celery.task.control import revoke
revoke(task_id, terminate=True)

to call revoke with the task_id of the task to stop.

And we set terminate to True to terminate the task.

Conclusion

To cancel an already executing task with Celery and Python, we can use the revoke function.

Categories
Python Answers

How to create multiple model instances with the Python Django Rest Framework?

To create multiple model instances with the Python Django Rest Framework, we can create a serialize with many set to True.

For instance, we write

class ThingSerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        many = kwargs.pop('many', True)
        super(ThingSerializer, self).__init__(many=many, *args, **kwargs)

    class Meta:
        model = Thing
        fields = ('loads', 'of', 'fields', )

to call the super class’ __init__ method with the many argument set to many.

If it’s True, then our serializer can accept multiple model instances.

Categories
Python Answers

How to generate file to download with Python Django?

To generate file to download with Python Django, we can use the HttpResponse class.

For instance, we write

from django.http import HttpResponse
from wsgiref.util import FileWrapper

response = HttpResponse(FileWrapper(myfile.getvalue()), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=myfile.zip'
return response

to generate the download file in our view by creating a HttpResponse object.

We call myfile.getvalue() to get the file and wrap it with FileWrapper where myfile is a Django File object.

And then we set the Content-Disposition header with

response['Content-Disposition'] = 'attachment; filename=myfile.zip'

And finally, we return the response.

Categories
Python Answers

How to use pagination with Python Django class based generic ListViews?

To use pagination with Python Django class based generic ListViews, w we can create our own view class that inherits from the ListView class.

For instance, we write

import models
from django.views.generic import ListView

class CarListView(ListView):
    model = models.Car      
    template_name = 'app/car_list.html' 
    context_object_name = "car_list"
    paginate_by = 10

to create the CarListView that returns the Car model values in paginated form in views.py.

We render the app/car_list.html template by writing

template_name = 'app/car_list.html' 

And we set paginate_by to 10 to return 10 items per page.

Then in car_list.html, we write

{% if car_list %}
    <table id="cars">
        {% for car in car_list %}
            <tr>
                <td>{{ car.model }}</td>
                <td>{{ car.year }}</td>
                <td><a href="/car/{{ car.id }}/" class="see_detail">detail</a></td>
            </tr>
        {% endfor %}
    </table>
    {% if is_paginated %}
        <div class="pagination">
            <span class="page-links">
                {% if page_obj.has_previous %}
                    <a href="/cars?page={{ page_obj.previous_page_number }}">previous</a>
                {% endif %}
                <span class="page-current">
                    Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
                </span>
                {% if page_obj.has_next %}
                    <a href="/cars?page={{ page_obj.next_page_number }}">next</a>
                {% endif %}
            </span>
        </div>
    {% endif %}
{% else %}
    <h3>My Cars</h3>
    <p>No cars found!!! :(</p>
{% endif %}

to render car_list items with a for loop.

And we if is_paginated is True.

If it is, then we render links to the previous and next page with previous_page_number and next_page_number .

Categories
Python Answers

How to filter empty or NULL names in a Python Django QuerySet?

To filter empty or NULL names in a Python Django QuerySet, we can caill the exclude method.

For instance, we write

Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')

to call exclude to exclude Name results that has alias set to null with

alias__isnull=True

And we exclude entries with alias set to an empty string by calling exclude with

alias__exact=''