하나의 모델에 여러 장의 이미지를 포함시키고 싶은 경우
# models.py
class Post(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=128)
body = models.CharField(max_length=400)
def get_image_filename(instance, filename):
id = instance.post.id
return "post_images/%s" % (id)
class Images(models.Model):
post = models.ForeignKey(Post, default=None)
image = models.ImageField(upload_to=get_image_filename,
verbose_name='Image')
# forms.py
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', )
# views.py
@login_required
def post(request):
ImageFormSet = modelformset_factory(Images,
form=ImageForm, extra=3)
if request.method == 'POST':
form = PostForm(request.POST)
formset = ImageFormSet(request.POST, request.FILES,
queryset=Images.objects.none())
if form.is_valid() and formset.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
for form in formset.cleaned_data:
image = form['image']
photo = Images(post=post, image=image)
photo.save()
messages.success(request,
"Posted!")
return HttpResponseRedirect("/")
else:
print form.errors, formset.errors
else:
form = PostForm()
formset = ImageFormSet(queryset=Images.objects.none())
return render(request, 'index.html',
{'postForm': form, 'formset': formset},
context_instance=RequestContext(request))
# index.html
<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 }} <br />
{% endfor %}
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
<input type="submit" name="submit" value="Submit" />
</form>
참고
(https://medium.com/@qasimalbaqali/upload-multiple-images-to-a-post-in-django-ff10f66e8f7a)
이부분에 bulk_insert로 변경해주시면 더 좋습니다