Home > Blockchain >  django multiple image upload
django multiple image upload

Time:03-20

Hi I am pretty new to Django and trying to let the user upload multiple images per project. The Django Documentation enter link description here shows how to do it in generell but I think I am rendering my form differently than they are doing it. So I don´t know how to add the 'multiple' attribute in my input field. In addition they have an extra class in their views.py and inside of that the function. Thanks for your help.

views.py

def createProject(request):
    form = ProjectForm()

    if request.method == 'POST':
        form = ProjectForm(request.POST, request.FILES)
        if form.is_valid():
            project = form.save(commit=False)
            project.save()

    context = {'form':form}
    return render(request, 'projects/project_form.html', context)

models.py

class Project(models.Model):
    title = models.CharField(max_length=200)
    featured_images = models.ImageField(null=True, blank=True, default="default.jpg")

forms.py

class ProjectForm(ModelForm):
    class Meta:
        model = Project
        fields = ['title', 'featured_images']

project_form.html

            <form  method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                {% for field in form %}
                <div >
                    <label for="formInput#text">{{field.label}}</label>
                    {{field}}
                </div>
                {% endfor %}
            </form>

CodePudding user response:

First you have to slightly adjust your form to allow for multiple upload:

# forms.py

class ProjectForm(ModelForm):
    class Meta:
        featured_images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
        model = Project
        fields = ['title', 'featured_images']

Then in the view you have to grab multiple entries:

# views.py 

def createProject(request):
    form = ProjectForm()

    if request.method == 'POST':
        form = ProjectForm(request.POST, request.FILES.getlist('featured_images'))
        if form.is_valid():
            project = form.save(commit=False)
            project.save()

    context = {'form':form}
    return render(request, 'projects/project_form.html', context)

Please let me know if that works.

CodePudding user response:

There are multiple ways to associate multiple images to a single field in Django. One way I like to do is:

  1. First create two models, one for the thing you want(in this case Project) and the other for images.
class MyModel(models.Model):
   field = models.CharField(max_lenght=255)

class MyModelImage(models.Model):
   image = models.ImageField(upload_to="/where_you_want_to")
   field = models.ForeignKey(MyModel,related_name="images",on_delete=models.CASECADE)

  1. Then using Django inline formset you can add multiple images at once.

I hope this helps you out

  • Related