Reputation: 125
html form:
<form action = "{% url 'newcomplaint' %}" class = 'newc' method = "post" enctype = "multipart/form-data" >
{ % csrf_token % }
<div class = "form-group" >
<label for = "fileToUpload" > Add an image(optional) < /label >
<input type = "file" name = "fileToUpload" id = "fileToUpload" >
</div >
<button type = "submit" class = "btn btn-dark bb" > Post New Complaint < /button >
</form >
views.py:
Here I am getting MultiValueDictKeyError at /hood/new
def newcomplaint(request):
if request.method == "POST":
# I dont know how to store a image here
image = request.FILES['fileToupload']
#print(image)
return HttpResponse('works')
model.py
from django.db import models
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
class Complain(models.Model):
image = models.ImageField(upload_to='images/', blank=True)
All the solutions that I see are done using django forms, I want to avoid that as I have made a bigger form with image field plus some other input (and added styling and Js check for validation).
So how to retrieve a file from a form and store it in django.
Upvotes: 0
Views: 454
Reputation: 125
I had a typo, also found a solution how to store a file/image in django without forms
my working code: views.py
def newcomplaint(request):
if request.method == "POST":
newcomplaint = Complain.objects.create(
user=request.user,
title=request.POST['title'],
content = request.POST['content'],
ran = request.POST['range'],
lati = request.POST['lati'],
longi = request.POST['longi'],
)
if len(request.FILES) == 0:
print('no files')
else:
_, file = request.FILES.popitem()
file = file[0]
newcomplaint.image = file
newcomplaint.save()
return HttpResponse('works')
Upvotes: 1
Reputation: 2084
There is a typo. You have written fileToupload
. It should be fileToUpload
Upvotes: 0
Reputation: 87054
Your code expects fileToupload
to be the key, however, your form uses fileToUpload
.
Upvotes: 1