GCP Bukalo
GCP Bukalo

Reputation: 53

How to get related model data in Django Admin panel?

I am developing a product base table and my product table is related to Informtion table, it means a product can have information, but when i add product from admin panel, i am not getting information data there when i submit the product, Please let me know how i can get the information table fields in product add form in django admin panel.

Here is my `models.py file...

class Product(models.Model):
    name=models.CharField(max_length=50, blank=True, null=True)
    type=models.CharField(max_length=50, blank=True, null=True)
    def __str__(self):
        return self.name

class Information(models.Model):
    product=models.ForeignKey(Product, default=None, related_name='product_info', on_delete=models.CASCADE)
    title=models.CharField(max_length=50, null=True, blank=True)
    number=models.IntegerField(default=None)

    def __str__(self):
        return self.title

my `admin.py' file is this

from django.contrib import admin
from customer.models import *
# Register your models here.
admin.site.register(Product)
admin.site.register(Information)

when i am clicking on add product it's displaying there only name, type and i want to display the data from information table also, i want all fields when i click on add product

Upvotes: 0

Views: 1337

Answers (2)

token
token

Reputation: 933

What you want is called Inline. Read more about here: Django Admin Inline

Upvotes: 0

subhanshu kumar
subhanshu kumar

Reputation: 392

Add this line to your admin:

from django.contrib import admin

class InformationInline(admin.TabularInline):
    model = Information

class productAdmin(admin.ModelAdmin):

    inlines = [InformationInline]

admin.site.register(Product,productAdmin)

and remove the below line:

admin.site.register(Product)

Now restart the server and go into your admin and now you can see all the information table data and edit it.

Upvotes: 1

Related Questions