30👍
✅
You have to add __unicode__(self)
or __str__(self)
methods in your models class.
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)
- Django: Duplicated logic between properties and queryset annotations
- How to add report section to the Django admin?
- Testing authentication in Django Rest Framework Views — Cannot authenticate when testing
- How to release the occupied GPU memory when calling keras model by Apache mod_wsgi django?
Source:stackexchange.com