Skip to content

Instantly share code, notes, and snippets.

@varqasim
Created August 22, 2015 18:17
Show Gist options
  • Save varqasim/c25b8cb627881bb6af1c to your computer and use it in GitHub Desktop.
Save varqasim/c25b8cb627881bb6af1c to your computer and use it in GitHub Desktop.
Uploading multiple images in Django using Fromset(modelformset_factory). Read more on my blogpost http://qasimalbaqali.com/uploading-multiple-images-in-django-for-a-single-post/
class PostForm(forms.ModelForm):
title = forms.CharField(max_length=128)
body = forms.CharField(max_length=245, label="Item Description.")
class Meta:
model = Post
fields = ('title', 'body', )
class ImageForm(forms.ModelForm):
image = forms.ImageField(label='Image')
class Meta:
model = Images
fields = ('image', )
<form id="post_form" method="post" action=""
enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in postForm.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in postForm %}
{{ field|as_crispy_field }} <br />
{% endfor %}
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
<input class="btn btn-danger btn-block"
type="submit" name="submit" value="Submit" />
</form>
@login_required
def post(request):
   ImageFormSet = modelformset_factory(Images,
                                       form=ImageForm, extra=3)
   if request.method == 'POST':
   
       postForm = PostForm(request.POST)
       formset = ImageFormSet(request.POST, request.FILES,
                              queryset=Images.objects.none())
   
   
       if postForm.is_valid() and formset.is_valid():
   
           human = True
   
           post_form = postForm.save(commit=False)
           post_form.user = request.user
           post_form.save()
   
           for form in formset.cleaned_data:
               image = form['image']
               photo = Images(post=post_form, image=image)
               photo.save()
           messages.success(request,
                            "Yeeew,check it out on the home page!)
           return HttpResponseRedirect("/")
       else:
           print postForm.errors, formset.errors
   else:
       postForm = PostForm()
       formset = ImageFormSet(queryset=Images.objects.none())
   return render(request, 'index.html',
                 {'postForm': postForm, 'formset': formset},
                 context_instance=RequestContext(request))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment