python - Django ajax上传图片

标签 python ajax django post upload

我尝试使用没有 Django 表单的 Ajax 上传图片。

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

我的代码:

View .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))

模型.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
        }
    });
});

最佳答案

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

为此,您必须创建 FormData,然后将文件添加到其中,可以在此处找到示例: Send Images Via Ajax .

或者,简单地使用已经存在的 jquery Ajax Form Plugin这会为您完成所有艰苦的工作。

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

关于python - Django ajax上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31866920/

相关文章:

python - 从线程调用PyObject_Call导致堆栈溢出

python - Huggingface 变形金刚模块未被 anaconda 识别

python - 在 Flask 应用程序中返回 Excel 文件

javascript - 如果 div 在 ajax 调用中动态加载,如何获取元素选择器

python - 一站式管理

django - 被 CORS 策略阻止 - 从 Django 应用程序访问 S3 存储桶

python - 无法使用 Django manage.py 创建 super 用户

javascript - 为什么我的 in for each 循环只添加最后一个元素?

javascript - 如何将链接(href)绑定(bind)到任何下拉选项?

python - Send_mail 未发送邮件至 gmail id。 [ Django ]