django-choices

2.0.0 · maintenance · verified Sat Apr 11

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

Install

Imports

Quickstart

Define choice sets using `DjangoChoices` and `ChoiceItem` classes, then integrate them into Django model fields. The `choices` attribute of your `DjangoChoices` class provides the iterable required by Django model fields.

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)

view raw JSON →