Reputation: 11
I want to upload a file and text from the same page to two Modals. I have created two forms on the same page, one is type=file
and the other one is type=text
.And two separate button
's for each form. And created two Modal Gallery_img
and Gallery_txt
. when I upload a file, it successfully get uploaded but when I then upload text its is showing error( mentioned below )
Iam Getting error: MultiValueDictKeyError: 'file'
Form:
<form id='form1' action="" method="post" enctype="multipart/form-data" >
{% csrf_token %}
<input type='file' name='file'>
<br>
<button type="submit" onclick='submitForm1()'>Ok</button>
</form>
<br>
<form id='form2' action="" method="post" >
{% csrf_token %}
<input type='text' name='text'>
<br>
<button type="submit" onclick='submitForm2()'> Okay</button>
</form>
//scripts for buttons
<script>
function submitForm1(){
document.getElementById('form1').submit();
};
function submitForm2(){
document.getElementById('form2').submit();
};
</script>
Modals:
class Gallery_img(models.Model):
gallery_image = models.ImageField( upload_to='img',max_length=None)
class Gallery_txt(models.Model):
gallery_text = models.CharField(max_length=8, null=True)
Views:
def gallery(request):
from .models import Gallery_img, Gallery_txt
if request.method== 'POST':
if request.FILES['file']:
post = Gallery_img()
post.gallery_image = request.FILES['file']
post.save()
print('successful image uplaod')
return render(request, 'gallery.html')
if request.POST.get('text'):
post= Gallery_txt()
post.gallery_text = request.POST.get('text')
post.save()
print('successful text uplaod')
return render(request, 'gallery.html')
else:
return render(request, 'gallery.html')
Upvotes: 1
Views: 417
Reputation: 11
Just edit the views.py
post.gallery_image = request.FILES.get('file')
Upvotes: 1