2

I have this models.py code where I want to get multiple values/file from single field without creating another table just for images.

Currently I am just repeating these field

class contentimage(models.Model):
content = models.ForeignKey(element, on_delete=models.CASCADE)
title = models.CharField(max_length=200)

titleimg1 = models.CharField(max_length=200)
image1 = models.ImageField(blank=True, upload_to='media/')
img1description = models.TextField()

titleimg2 = models.CharField(max_length=200)
image2 = models.ImageField(blank=True, upload_to='media/')
img2description = models.TextField()

titleimg3 = models.CharField(max_length=200)
image3 = models.ImageField(blank=True, upload_to='media/')
img3description = models.TextField()

titleimg4 = models.CharField(max_length=200)
image4 = models.ImageField(blank=True, upload_to='media/')
img4description = models.TextField()

titleimg5 = models.CharField(max_length=200)
image5 = models.ImageField(blank=True, upload_to='media/')
img5description = models.TextField()

An optimal output will be an input field in django admin where a plus sign can add multiple images It would be really very helpful if someone can just guide me in the right direction.

1 Answer 1

1

Make the images into Inlines. First give them their own model class:

class Image(models.Model):
    content = models.ForeignKey(contentimage, on_delete=PROTECT). # this is what connect the two models
    title = models.CharField(max_length=200)
    image = models.ImageField(blank=True, upload_to='media/')
    description = models.TextField()

Then register the class in the admin:

class ImageInlineAdmin(admin.InlineModelAdmin):
    extra = 0
    model = Image

And then register the inline in your contentimage admin with a line:

inlines = [ImageInlineAdmin]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.