How to Upload Multiple Images in Django?

0
382
How to Upload Multiple Images in Django?

In this tutorial we will learn how to add multiple images in Django Model, So let’s start

You’ll just need two models. One for the Product and the other would be for the ProductImage model. Your image model would have a foreign key to the Product model:

Step 1: Go to models.py file in your admin app (Or your created app), and create Product and ProductImage model class

class Product(models.Model):
    name=models.CharField(max_length=225)
    slug=models.SlugField(max_length=225, unique=True)
    image= models.ImageField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    def save(self,*args, **kwargs):
        self.slug = slugify(self.name)
        #unique_slugify(self, cat_slug_str)
        super(Product, self).save(*args, **kwargs)
class ProductImage(models.Model):
product=models.ForeignKey(Product, default=None, on_delete=models.CASCADE)
image=models.ImageField(upload_to='product_image')

def __str__(self):
return self.product.name

Step 2: Now Add this image filed in your forms.py file, in that case if your are submitting data through forms.py file

Step 3: No need to change in your views.py file if you are working with forms.py file

it's your views.py file 

def create_product(request):
    subcat=SubCategory.objects.all()
    form = ProductForm(request.POST)
    if form.is_valid():
        newpost = form.save(commit=False)
        newpost.slug = slugify(newpost.name)
        newpost.save()
    context={
        'subcat':subcat, 'form':form,
    }
    return render(request, 'home.html', context)

Step 4: Now go to admin.py file and add this code there

from django.contrib import admin
# Register your models here.
from .models import Product, ProductImage

class ProductImageAdmin(admin.StackedInline):
    model = ProductImage

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    inlines = [ProductImageAdmin]

    class Meta:
        model=Product

@admin.register(ProductImage)
class ProductImageAdmin(admin.ModelAdmin):
    pass

Result: Finally Run the Migrations, and check your admin panel, You will find something link this in your product model forms.

Database: And now lets add product in our database, and we will check the database table now.

LEAVE A REPLY

Please enter your comment!
Please enter your name here