About Model Choice Fields
By default, django.forms.ModelChoiceField
uses the __str__()
method of the model to represent the items in the option list.
When your __str__()
representations are not unique, you can extend the ModelChoiceField
and overwrite the label_from_instance(self, obj)
method and display custom unique options:
from django.forms import ModelChoiceField
class ModelChoiceFieldWithIDs(ModelChoiceField):
def label_from_instance(self, obj):
return f"{obj.title} (ID={obj.pk})"
Tips and Tricks Programming User Experience Django 4.2 Django 3.2 Django 2.2 Python 3
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.