although, there are many topics for this, i cannot find the right question+answer among them
my problem is this:
i am trying to write an file upload. once i submit the form, this error is coming:
MultiValueDictKeyError at /anzeige_save/
Key 'file' not found in <MultiValueDict: {}>
this is my model:
class Anzeige(models.Model):
titel = models.CharField(max_length=300)
anzeige = models.CharField(max_length=1000)
date = models.DateTimeField()
datum = models.CharField(max_length=12)
file = models.FileField(upload_to='/anzeige/D-d-M-Y/')
def __unicode__(self):
return self.titel
this is my view:
if request.path == '/anzeige_save/':
anzeige=Anzeige(titel=request.POST['titel'], anzeige=end_anzeige,date=datetime.datetime.now(), datum=request.POST['datum'],file=request.FILES['file'])
anzeige.save()
return HttpResponse("Anzeige saved successfully")
this is my ajax in front-end:
var title = document.getElementById(title).value;
var body = document.getElementById(body).value;
var file = document.getElementById(name_file).value;
var datum = document.getElementById(datum).value;
if(title==" " || body==" " || title=="" || body=="" || datum=="" || datum==" " ){
alert("Please fill out all!");
}else{
$.ajax({
url: "/anzeige_save/",
type: "POST",
data: {anzeige:body,titel:title,file:file,datum:datum},
}).success(function(data){
$(succ_message).text(data);
$(succ_message).fadeIn(1000);
$(succ_message).fadeOut(2000);
})
}
and this is file in form:
...
<input type="file" id="name_file" name="name_file" size="40" maxlength="100000"><br />
...
am i missing something here ?
i have Model with filefield and i am saving other fields including file into instance.
thanks for any drop-by! 🙂
Make sure your form is multipart:
Forgetting this is a common cause of your error.
EDIT: File uploads are not possible through ajax*. There are a few options: