Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying the model's__unicode__ in django admin

Tags:

I would like to display the model's username in Django Admin interface but not very sure how to do it..

The models.py:      class Adult(models.Model):             user = models.OneToOneField(User)         fullname = models.CharField(max_length=100,                                     blank=True)         def __unicode__(self):             return self.user.username  Admin.py:      class AdultAdmin(admin.ModelAdmin):         list_display = ('??', 'Student_Name',)         search_fields = ['??',]      admin.site.register(Adult, AdultAdmin) 

What should go inside the ?? above ? I would like to display the unicode or the self.user.username? How do i do it? Need some guidance...

like image 921
lakshmen Avatar asked Aug 13 '12 03:08

lakshmen


People also ask

How do we register a model with Django admin?

If the Django project has too many models or if it has a legacy database, then adding all those models to admin becomes a tedious task. To automate this process, we can programmatically fetch all the models in the project and register them with the admin interface. Open admin.py file and add this code to it.

What is model admin in Django?

The modeladmin module allows you to add any model in your project to the Wagtail admin. You can create customisable listing pages for a model, including plain Django models, and add navigation elements so that a model can be accessed directly from the Wagtail admin.

Is Django's admin interface customizable if yes then how?

In this article, we will discuss how to enhance Django-admin Interface. Let us create an app called state which has one model with the same name(state). When we register app to admin.py it shows like. Now lets' customize django admin according to available options.


1 Answers

From the list_display documentation there are four things you can add there:

  1. A field
  2. Some method (a callable) that accepts one variable that is the instance for which the row is being displayed.
  3. A string that is the name of a method or attribute defined in the model class.
  4. A string that is the name of a method that is defined in ModelAdmin.

For your case we need #3 for list_display.

For search_fields its easier as you can use follow notation (__) to do lookups.

In the end we come up with this:

class AdultAdmin(admin.ModelAdmin):     list_display = ('__unicode__', 'Student_Name',)     search_fields = ['user__username'] 
like image 109
Burhan Khalid Avatar answered Sep 20 '22 03:09

Burhan Khalid