django-choices
Django-choices provides a declarative way of using the `choices` option on Django fields, aiming to add order and sanity to Django model choices. The current version is 2.0.0. While it served a valuable purpose, the library is now in maintenance mode, with its maintainers strongly recommending migration to native Django 3.0+ `TextChoices` or `IntegerChoices` for new projects due to Django's improved built-in functionality.
Warnings
- deprecated The `django-choices` library is no longer actively developed, and its use is strongly discouraged for new projects. Django 3.0+ introduced native enumeration types (`TextChoices`, `IntegerChoices`) that largely supersede the functionality provided by this package.
- gotcha There are several similarly named packages (e.g., `django-choices-field`, `django-js-choices`) that serve different purposes. Ensure you are installing and importing from the correct `django-choices` library by `bigjason`.
- gotcha The module to import from is `djchoices`, not `django_choices` or `django.choices`. This is a common point of confusion.
Install
-
pip install django-choices
Imports
- DjangoChoices
from djchoices import DjangoChoices
- ChoiceItem
from djchoices import ChoiceItem
- C
from djchoices import C
Quickstart
import os
import django
from django.conf import settings
from django.db import models
# Minimal Django settings for standalone script
settings.configure(
INSTALLED_APPS=['test_app'],
DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}},
USE_I18N=True, # Required for ugettext_lazy if used in ChoiceItem
)
django.setup()
from djchoices import ChoiceItem, DjangoChoices
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
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, on_delete=models.CASCADE)
book_type = models.CharField(
max_length=20,
choices=BookType.choices,
default=BookType.novel
)
def __str__(self):
return f"{self.book_type.label} by {self.author.name}"
# Example usage (requires an actual Django project setup normally)
if __name__ == '__main__':
# This part would typically be in your Django ORM interaction code
# For this example, we'll just demonstrate the choice access.
print(f"Book type choices: {Book.BookType.choices}")
print(f"Default book type value: {Book.BookType.novel.value}")
print(f"Default book type label: {Book.BookType.novel.label}")
# In a real Django setup, you would create and query model instances.
# Example of accessing choices directly:
status_options = []
for value, label in Book.BookType.choices:
status_options.append(f"Value: {value}, Label: {label}")
print("\nAvailable Book Types:")
for option in status_options:
print(option)