开发者

Why django admin sometimes uses some field of the model in the index, instead of __unicode__ method?

For some of my models, Django-admi开发者_JAVA百科n, in the index of the model's objects, instead of displaying the output of the __unicode__ method like normally, it just displays one of the model's fields there.

This happens usually when there is something like:

class Meta:
    ordering = ['name']

in my model, then the value of the field name is displayed (even though there is also a __unicode__ method), but not always, sometimes it just displays what __unicode__ says even if there is a class Meta ordering.

All my Unicode methods are quite normal, something like:

def __unicode__(self):
    return u'[%s] %s' % (self.field, self.name, )

I am puzzled, why is a field used sometimes instead of __unicode__, and how can I make it use the __unicode__ method always? This is Django 1.3. Is this a bug in Django?


You can customise the fields displayed in the django admin using the list_display option in your ModelAdmin class.

The model __unicode__ method, and the Meta.ordering option do not have any affect on the fields displayed.

If you do not set list_display, then the default behaviour is to display a single column with the unicode string for each object.

If the unicode string is not displayed for your model, it sounds like you have set list_display. For example, to display the name field instead of the unicode string, you would do:

class MyModelAdmin(models.ModelAdmin):
    list_display = ['name'] 

If you want to display the unicode string and other fields, simply include __unicode__ in list_display.

class MyModelAdmin(models.ModelAdmin):
    list_display = [`__unicode__`, 'name'] 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜