Home > OS >  Django Models return fields as columns for Django Admin
Django Models return fields as columns for Django Admin

Time:12-28

I looked a lot but I couldn't find a way to return my model to django admin with the columns not only the model name:

What I wish to accomplish from my model is to have the fields represent columns in Django admin, as it is in users:

enter image description here

I have a model called Products:

from django.db import models

# Create your models here.
class Product(models.Model):
    title = models.CharField(max_length=30, null=False, blank=False)
    price = models.FloatField(null=False, blank=False)
    description = models.CharField(max_length=250, null=False, blank=False)
    longDescription = models.TextField(max_length=900, null=True, blank=True)

    def __str__(self):
        return self.title

It registers on admin site as I can see it as:

enter image description here

I'm looking for a way to have my products listed as users, with the id, price, description as columns... Is it possible?

Thanks in advance!

CodePudding user response:

You should fill ModelAdmin.list_display for your ProductAdmin like this

class ProductAdmin(ModelAdmin):
    list_display = ['id', 'price', 'description']

CodePudding user response:

This is complete sample of the admin.py
I add the search option as well just in case you want those fields to be searchable.


from django.contrib import admin
from .models import Product


class ProductAdmin(admin.ModelAdmin): 
    list_display = ('id','title ', 'price ', 'description ','longDescription ')
    search_fields =['title ', 'price ', 'description ','longDescription '] 


admin.site.register(Product,ProductAdmin)

  • Related