Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two models and make only one form in admin section?

I have two models Products and ProductImages. But i have to submit those differently from admin section. Is there is any option to combine all the fields of two models in a single form in admin. i have one to many relationship between products and images.

class Products(models.Model):

   product_name = models.CharField(max_length = 50)
   sku = models.CharField(max_length = 50)
   details = models.TextField(null = True)
   price = models.FloatField(default='0.00')
   created_at = models.DateTimeField(auto_now_add=True)
   updated_at = models.DateTimeField(auto_now=True)

   def __unicode__(self):
    return '%s %s' % (self.product_name, self.sku)

class ProductImages(models.Model):

   product = models.ForeignKey('Products', on_delete=models.CASCADE)
   images = models.ImageField(upload_to = 'images/product_images/', default = '')
   created_date = models.DateTimeField(auto_now_add=True)`enter code here`
   updated_date = models.DateTimeField(auto_now=True)
like image 583
Snigdhadeep Avatar asked Feb 05 '23 19:02

Snigdhadeep


1 Answers

You can use InlineModelAdmin, see https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.

admin.py:

from django.contrib import admin

class ProductImagesInline(admin.TabularInline):
    model = ProductImages

class ProductsAdmin(admin.ModelAdmin):
    inlines = [
        ProductImagesInline,
    ]
like image 173
illagrenan Avatar answered Apr 27 '23 04:04

illagrenan