Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python DjangoAjax上传图像_Python_Ajax_Django_Post_Upload - Fatal编程技术网

Python DjangoAjax上传图像

Python DjangoAjax上传图像,python,ajax,django,post,upload,Python,Ajax,Django,Post,Upload,我尝试上传图像,使用Ajax而不使用django表单 它不会返回错误。 一切正常,它保存在数据库“名称”和“描述”中,但不保存“图像”:( 我的代码: views.py def add(request): articles = Article.objects.all() if request.method == 'POST': if request.is_ajax(): name = request.POST.get('name') descriptio

我尝试上传图像,使用Ajax而不使用django表单

它不会返回错误。 一切正常,它保存在数据库“名称”和“描述”中,但不保存“图像”:(

我的代码:

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


这里的问题是Ajax代码,您不能通过变量直接发送图像

要执行此操作,您必须创建FormData,然后将文件添加到其中,下面是一个示例:

或者,简单地使用已经存在的为你做所有艰苦工作的工具

您的选择,希望这有帮助:)

 <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>
 //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
        }
    });
});