Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set django admin to display all the columns of the database

Tags:

I am using django to create a website for my school project, but the thing is django admin doesn't represent its database like xamp does (tables, rows columns), instead it displays just one column. Is there anyway I can set it to bring out all the information in the database just like in xamp or wamp

like image 559
Michael Avatar asked Aug 03 '19 18:08

Michael


2 Answers

list_display is used to show the columns in the admin table. To show column you need to pass columns names like below:

Example:

list_display = ('first_name', 'last_name')

To display all the columns of your model in admin

list_display = [field.name for field in YOURMODEL._meta.get_fields()]

In our case:

list_display = [field.name for field in Setting._meta.get_fields()]

models.py

from django.db import models
from django.contrib import admin

# Create your models here.
class Home(models.Model):
    image = models.ImageField(upload_to='uploads')

class Setting(models.Model):
    key = models.CharField(max_length=100, verbose_name='Key')
    value = models.TextField(verbose_name='Value')

admin.py

from django.contrib import admin
from .models import Home
from .models import Setting

# Register your models here.

class SettingAdmin(admin.ModelAdmin):
    list_display = ('key', 'value')

admin.site.register(Home)
admin.site.register(Setting, SettingAdmin)

enter image description here

like image 189
Mayank Dudakiya Avatar answered Sep 30 '22 15:09

Mayank Dudakiya


I hope you migrate your database through django models, then you're looking for list_display. So you define all the models in the models.py and there is another file call admin.py.

from django.contrib import admin

from models import <Your_Model_Name>


class Admin<Your_Model_Name>(admin.ModelAdmin):
    model = <Your_Model_Name>
    list_display = ('column1', 'column2', 'column3')


admin.site.register(<Your_Model_Name>, Admin<Your_Model_Name>)

Your models.py should similar to this one,

from django.db import models


class Your_Model_Name(models.Model):
    column1 = models.CharField(max_length=100)
    column2 = models.CharField(max_length=100)
    column3 = models.CharField(max_length=100)

    def __str__(self):
        return self.column1 

If you are seeing only one column mean which is define under def __str__(self) function. Now you'll display other columns too. If you want to display all the columns, you can try below code line by using Options.get_fields().

list_display = <Your_Model_Name>._meta.get_fields()
like image 34
Kushan Gunasekera Avatar answered Sep 30 '22 15:09

Kushan Gunasekera