Customizing a Django Admin panel, I'm using raw_id_fields
to select a ForeignKey from a Model which has thousands of elements, because the default select-box drop-down is inconvenient with so many elements.
It works but it shows the id as can be seen on this image:
Is there any way to show the name or other field instead of the id? Or, is there any better way to accomplish this than using raw_id_fields
?
This is my code in models.py
:
class Structure(MPTTModel):
name = models.CharField(max_length=200, unique=True, verbose_name = _('name'))
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', verbose_name = _('parent'))
def __unicode__(self):
return u"%s" % (self.name)
In admin.py
:
class StructureAdmin(tree_editor.TreeEditor):
search_fields = ('name',)
raw_id_fields = ('parent',)
From Django 2.0 you can use autocomplete_fields
. It will work just like ajax select2.
In admin.py
class StructureAdmin(tree_editor.TreeEditor):
search_fields = ('name',)
autocomplete_fields = ('parent',)
Reference: https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields
I've also researched this and I don't think it's possible. I think the best you can do is display the unicode of the field next to the raw id field: http://djangosnippets.org/snippets/2108/
Alternatively, you can display the unicode and a link to the value's corresponding admin change page: http://djangosnippets.org/snippets/2217/
It seems this plugin: https://github.com/lincolnloop/django-dynamic-raw-id
does what you want:
(copied from the doc):
Usage
To start using django-dynamic-raw-id in your application all you need to do is implement DynamicRawIDMixin in your ModelAdmin class and add the desired fields to a list of dynamic_raw_id_fields:
from dynamic_raw_id.admin import DynamicRawIDMixin
class UserProfileAdmin(DynamicRawIDMixin, admin.ModelAdmin):
dynamic_raw_id_fields = ('user',)
You can use dynamic_raw_id widgets in a Admin filter as well:
from dynamic_raw_id.admin import DynamicRawIDMixin
from dynamic_raw_id.filters import DynamicRawIDFilter
class UserProfileAdmin(DynamicRawIDMixin, admin.ModelAdmin):
list_filter = (
('dynamic_raw_id_fk', DynamicRawIDFilter),
)
For the representation of an object use __unicode__
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
In Python 3 use
def __str__(self):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With