2

I try to upload image, using Ajax without django forms.

It not return errors. Everything it's ok, it save in database "name" and "description" but not save "image" :(

My code:

views.py

def add(request): articles = Article.objects.all() if request.method == 'POST': if request.is_ajax(): name = request.POST.get('name') description = request.POST.get('description') icon = request.FILES.get('icon') article_new = Article( name=name, description=description, icon=icon ) article_new.save() return render_to_response('home.html', {'articles':articles}, context_instance=RequestContext(request)) 

models.py

 class Article(models.Model): name = models.CharField(max_length=100, null=True, blank=True) description = models.TextField() icon = ThumbnailerImageField(upload_to='uploads') 

html

 <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" id="inputName"> <input type="text" id="inputDescription"> <input type="file" id="inputFile"> <button id="submit" type="submit">Add</button> </form> 

javascript

 //For doing AJAX post $("#submit").click(function(e) { e.preventDefault(); var name = $('#inputName').val(); var description = $('#inputDescription').val(); var icon = $('#inputFile').val(); //This is the Ajax post.Observe carefully. It is nothing but details of where_to_post,what_to_post $.ajax({ url : "/add", // the endpoint,commonly same url type : "POST", // http method data : { csrfmiddlewaretoken : csrftoken, name : name, description : description, icon: icon }, // data sent with the post request // handle a successful response success : function(json) { console.log(json); // another sanity check }, // handle a non-successful response error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); }); 
1
  • Hey, did you found the answer, I mean the code. Because I am trying to the same thing and is not working for me. Please post a proper answer if you got one :-) Commented Feb 25, 2022 at 8:05

1 Answer 1

7

The issue here is with the Ajax code, you cannot directly send the image via a variable.

To do so, you would have to create FormData and then add the file to it, an example can be found here: Send Images Via Ajax.

Or, simply use the already existing jquery Ajax Form Plugin which does all the hard work for you.

Your choice, hope this helps :)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.