Django - Multiple Images for product in Django Admin Page

Mahabubur Rahman
0

In the Django default admin panel, we can add an app model. 

Today I will show how to add a model with a formset. I will show how you add multiple images for a single product in the Django default admin panel.


Here are our models - 

class Product(models.Model):
name = models.CharField(max_length=255, null=False, blank=False)
slug = models.SlugField(max_length=200, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)

def __str__(self):
return self.name

def get_absolute_url(self):
return reverse('shop:product_detail',
args=[self.category.slug, self.slug])
class Images (models.Model):
product = models.ForeignKey(Product, default=None, related_name='images', on_delete=models.CASCADE)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)

add abode models in your add model.py

After creating models, you need to run two commend in order to create database tables for models.

python manage.py makemigrations

python managepy migrate

then add the bellow code in admin.py of your app - 

class ProductImagesInline(admin.StackedInline):
model = Images

class ProductAdmin(admin.ModelAdmin):
inlines = [ProductImagesInline]

admin.site.register(Product, ProductAdmin)

now go to the Django admin page and navigate to product > add. the form will as bellow - 








Post a Comment

0Comments
Post a Comment (0)