Search code examples
djangouploadmodels

Uploading multiple images with Django


I am working on a Django app and am having some trouble with the models/forms/templates required to upload images. I have a post and I want there to be a One-to-Many relationship with posts and images. i.e. A post can have any number of images. My first question is - what would the model look like? I am guessing something like:

class Image(models.Model):
    img = models.ImageField(upload_to="photos/",null=True, blank=True)
    posting = models.ForeignKey(Posting, related_name="images")

class Posting(models.Model):
    ...

Is this correct? And my other question is how should I upload multiple images? And I can't figure out what the form should look like. If I want to set a max number of images, could I just go like:

class ImageForm(forms.ModelForm):
    img1 = forms.ImageField()
    img2 = forms.ImageField()

    class Meta:
        model = Image
        fields = ('img1','img2',)

But then I have no idea how to look that up to the view correctly. I am super lost, any help would be greatly appreciated!


Solution

  • For this task you should use the inline formsets. Read this docs first for basic understanding of the formsets.

    The models in your question are almost valid. Remove the null=True, blank=True arguments from the img field - there is no sense in the Image instances without image itself.