[Fixed]-Django admin foreign key drop down field list only "test object"

30👍

You have to add __unicode__(self) or __str__(self) methods in your models class.

http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#django.db.models.Model.unicode

7👍

Had the same problem. Adding

def __str__(self):
    return self.user

solved the problem.

👤Ghasem

2👍

Sometimes you want to have different info returned from str function but Want to show some different info in the dropdown of admin. Then Above mentioned solution won’t work.

You can do this by subclassing forms.ModelChoiceField like this.

class TestChoiceField(forms.ModelChoiceField):
 def label_from_instance(self, obj):
     return "Test: {}".format(obj.id)

You can then override formfield_for_foreignkey

def formfield_for_foreignkey(self, db_field, request, **kwargs):
  if db_field.name == 'test':
    return TestChoiceField(queryset=Test.objects.all())
  return super().formfield_for_foreignkey(db_field, request, **kwargs)

Leave a comment