Django-Choices

Order and sanity for django model choices.

Build status Code quality checks Code coverage Documentation Status black pypi python-versions django-versions

Contents:

Overview

Warning

We strongly recommend migrating to the native functionality and not use django-choices for new projects. See the Migrating to native Django Choices. This library will not be actively developed any longer.

Django choices provides a declarative way of using the choices option on django fields.

Note: Django 3.0 added enumeration types. This feature mostly replaces the need for Django-Choices. See also Adam Johnson’s post on using them.

Requirements

Django choices is fairly simple, so most Python and Django versions should work. It is tested against Python 3.8+ and Django 3.2+.

Quick-start

Install like any other library:

pip install django-choices

There is no need to add it in your installed apps.

To use it, you write a choices class, and use it in your model fields:

from djchoices import ChoiceItem, DjangoChoices


class Book(models.Model):

    class BookType(DjangoChoices):
        short_story = ChoiceItem('short', 'Short story')
        novel = ChoiceItem('novel', 'Novel')
        non_fiction = ChoiceItem('non_fiction', 'Non fiction')


    author = models.ForeignKey('Author')
    book_type = models.CharField(
        max_length=20, choices=BookType.choices,
        default=BookType.novel
    )

You can then use the available choices in other modules, e.g.:

from .models import Book

Person.objects.create(author=my_author, type=Book.BookTypes.short_story)

The DjangoChoices classes can be located anywhere you want, for example you can put them outside of the model declaration if you have a ‘common’ set of choices for different models. Any place is valid though, you can group them all together in choices.py if you want.

License

Licensed under the MIT License.

Source Code and contributing

The source code can be found on github.

Bugs can also be reported on the github repository, and pull requests are welcome. See Contributing for more details.

Indices and tables