BaseCommand Example Code

BaseCommand is a Django object for creating new Django admin commands that can be invoked with the script. The Django project team as usual provides fantastic documentation for creating your own commands. There are also some well-written community tutorials on the subject such as How to Create Custom Django Management Commands by Vitor Freitas.

Example 1 from django-filer

django-filer (project documentation) is a file management library for uploading and organizing files and images in Django's admin interface. The project also installs a few Django commands to make it easier to work with the files and images that you upload. The project's code is available under the BSD 3-Clause "New" or "Revised" open source license.

django-filer / filer / management / commands /

# -*- coding: utf-8 -*-
from import BaseCommand

from filer.models.imagemodels import Image

class Command(BaseCommand):

    def handle(self, *args, **options):
        Generates image thumbnails
        NOTE: To keep memory consumption stable avoid iteration 
        over the Image queryset
        pks = Image.objects.all().values_list('id', flat=True)
        total = len(pks)
        for idx, pk in enumerate(pks):
            image = None
                image = Image.objects.get(pk=pk)
                self.stdout.write(u'Processing image {0} / {1} {2}'.\
                    format(idx + 1, total, image))
            except IOError as e:
                self.stderr.write('Failed to generate thumbnails: {0}'\
                del image

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2019