How to show all fields of model in admin page?

2020-05-14 14:06发布

here is the models page

In this picture, only the title shows up on here, I used:

 def __unicode__(self):
        return self.title;  

here is the each individual objects

How do I show all these fields?

How do I show all the fields in each Model page?

9条回答
Explosion°爆炸
2楼-- · 2020-05-14 14:35

If you want to include all fields without typing all fieldnames, you can use

list_display = BookAdmin._meta.get_all_field_names()

The drawback is, the fields are in sorted order.

Edit:

This method has been deprecated in Django 1.10 See Migrating from old API for reference. Following should work instead for Django >= 1.9 for most cases -

list_display = [field.name for field in Book._meta.get_fields()]
查看更多
来,给爷笑一个
3楼-- · 2020-05-14 14:42

By default, the admin layout only shows what is returned from the object's unicode function. To display something else you need to create a custom admin form in app_dir/admin.py.

See here: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display

You need to add an admin form, and setting the list_display field.

In your specific example (admin.py):

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'price')
admin.site.register(Book, BookAdmin)
查看更多
我只想做你的唯一
4楼-- · 2020-05-14 14:46

Every solution found here raises an error like this

The value of 'list_display[n]' must not be a ManyToManyField.

If the model contains a Many to Many field.

A possible solution that worked for me is:

list_display = [field.name for field in MyModel._meta.get_fields() if not x.many_to_many]

查看更多
登录 后发表回答