Ed.
Ed.

Reputation: 4577

In Django admin how do I display the verbose name in the dropdown of a generic foreign key

I have a model defined as:

class Feature(models.Model):
    content_type = models.ForeignKey(ContentType)
    user = models.ForeignKey(User, unique = True)
    object_id = models.PositiveIntegerField()
    description = models.TextField("Description", blank=False)
    content_object = generic.GenericForeignKey('content_type', 'object_id')

In the django admin site, the drop down for content_type shows all of the tables, but as their defined names, not the verbose names. How can I change this to show the pretty names instead of the coded names?

Upvotes: 2

Views: 3603

Answers (1)

Ian Clelland
Ian Clelland

Reputation: 44112

Without changing the ContentType model, You can do this by customizing the ModelAdmin that you use for your Feature model. Specifically, you can override the formfield_for_foreignkey method that defines the field that is used for every foreign key on your model.

You will have to define a custom ModelChoiceField as well, which overrides the normal labels used by the dropdown.

In your admin.py:

from django.contrib import admin
from django.forms import ModelChoiceField
from myproject.myapp.models import Feature

class CustomContentTypeChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "Pretty name for #%d" % obj.id

class FeatureAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "content_type":
            return CustomContentTypeChoiceField(**kwargs)
        return super(FeatureAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

admin.site.register(Feature, FeatureAdmin)

References:

Customizing admin form fields: https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey

ModelChoiceFields: https://docs.djangoproject.com/en/1.3/ref/forms/fields/#modelchoicefield

Upvotes: 5

Related Questions