Home > Net >  How can I dispay the data in django admin panel
How can I dispay the data in django admin panel

Time:02-10

I am creating an eCommerce website but I want to know how can I display a product_name or customer_name in the admin panel.

The concept is that if a customer places an order that it will go to the admin panel. So the other details are displaying properly except product_name or customet_name.

As shown in the below image:

enter image description here

models.py

class Order(models.Model):
        product = models.ForeignKey(Product, on_delete=models.CASCADE)
        customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
        quantity = models.IntegerField(default=1)
        address = models.CharField(max_length=50, default='', blank=True)
        phone = models.CharField(max_length=50, default='', blank=True)
        price = models.IntegerField()
        date = models.DateField(default=datetime.datetime.today)
        status = models.BooleanField(default=False)

admin.py

class AdminOrders(admin.ModelAdmin):
    list_display = ['product', 'customer', 'quantity', 'address', 'phone', 'price', 'date', 'status']

CodePudding user response:

You need to define the __str__ method in the models Product and Customer

Example:

def __str__(self):
    return self.name

CodePudding user response:

Have tried double underscore in order to access the foreign item field (product__name) and (customer__name).

class Product(models.Model):
   name= models.CharField(max_length=50, default='', blank=True)
   ....
class Customer(models.Model):
   name= models.CharField(max_length=50, default='', blank=True)
   ....

class AdminOrders(admin.ModelAdmin):
    list_display = ['product__name', 'customer__name', 'quantity', 'address', 'phone', 'price', 'date', 'status']

CodePudding user response:

If you call a function it have to return string if you want to display as word. I know 2 ways to do this First its repr Method

def __repr__(self):
     return self.(Model You wanna Display)

or str Witch is akcually same

def __str__(self):
     return self.(Model You wanna Display)
       
  • Related