|
| 1 | +title: django.core.management.base BaseCommand Examples |
| 2 | +category: page |
| 3 | +slug: django-core-management-base-basecommand-examples |
| 4 | +sortorder: 50018 |
| 5 | +toc: False |
| 6 | +sidebartitle: django.core.management.base BaseCommand |
| 7 | +meta: Python code examples for Django management commands. |
| 8 | + |
| 9 | + |
| 10 | +# django.core.management.base BaseCommand Examples |
| 11 | +[BaseCommand](https://github.com/django/django/blob/master/django/core/management/base.py) |
| 12 | +is a [Django](/django.html) object for creating new Django admin commands |
| 13 | +that can be invoked with the `manage.py` script. The Django project team |
| 14 | +as usual provides |
| 15 | +[fantastic documentation](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) |
| 16 | +for creating your own commands. There are also some well-written community |
| 17 | +tutorials on the subject such as |
| 18 | +[How to Create Custom Django Management Commands](https://simpleisbetterthancomplex.com/tutorial/2018/08/27/how-to-create-custom-django-management-commands.html) |
| 19 | +by Vitor Freitas. |
| 20 | + |
| 21 | + |
| 22 | +## Example 1 from django-filer |
| 23 | +[django-filer](https://github.com/divio/django-filer) |
| 24 | +([project documentation](https://django-filer.readthedocs.io/en/latest/)) |
| 25 | +is a file management library for uploading and organizing files and |
| 26 | +images in Django's admin interface. The project also installs a few |
| 27 | +Django `manage.py` commands to make it easier to work with the files |
| 28 | +and images that you upload. |
| 29 | + |
| 30 | +[**django-filer/filer/management/commands/generate_thumbnails.py**](https://github.com/divio/django-filer/blob/develop/filer/management/commands/generate_thumbnails.py) |
| 31 | + |
| 32 | +```python |
| 33 | +# -*- coding: utf-8 -*- |
| 34 | +~~from django.core.management.base import BaseCommand |
| 35 | + |
| 36 | +from filer.models.imagemodels import Image |
| 37 | + |
| 38 | + |
| 39 | +~~class Command(BaseCommand): |
| 40 | + |
| 41 | +~~ def handle(self, *args, **options): |
| 42 | + """ |
| 43 | + Generates image thumbnails |
| 44 | + NOTE: To keep memory consumption stable avoid iteration over the Image queryset |
| 45 | + """ |
| 46 | + pks = Image.objects.all().values_list('id', flat=True) |
| 47 | + total = len(pks) |
| 48 | + for idx, pk in enumerate(pks): |
| 49 | + image = None |
| 50 | + try: |
| 51 | + image = Image.objects.get(pk=pk) |
| 52 | + self.stdout.write(u'Processing image {0} / {1} {2}'.format(idx + 1, total, image)) |
| 53 | + self.stdout.flush() |
| 54 | + image.thumbnails |
| 55 | + image.icons |
| 56 | + except IOError as e: |
| 57 | + self.stderr.write('Failed to generate thumbnails: {0}'.format(str(e))) |
| 58 | + self.stderr.flush() |
| 59 | + finally: |
| 60 | + del image |
| 61 | +``` |
| 62 | + |
| 63 | + |
| 64 | + |
0 commit comments