class ModelBrowseField(forms.ChoiceField): """ Browse through the installed models using the content types framework. There are two difference in behavior with respect to the default field: 1. if a model provides a translation (e.g.: verbose_name and/or verbose_name_plural), we show that rather than a raw model name 2. allow to filter the models shown """ def __init__(self, choices=None, *args, **kwargs): from django.contrib.contenttypes.models import ContentType qs = ContentType.objects.all() if choices: # if there's a list of allowed models, filter the queryset choices = list(choices) # labels are all lowercase choices = [choice.lower() for choice in choices] qs = qs.filter(model__in=choices) choices = qs.values_list('id', 'name') # translate items (if available) newchoices = [] for id, choice in choices: id, mclass = id, ContentType.objects.get(pk=id).model_class() if mclass: newchoices.append((id, mclass._meta.verbose_name)) choices = newchoices choices.insert(0, ('', '---------')) super(ModelBrowseField, self).__init__(choices=choices, *args, **kwargs)