程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

在django应用程序中使用ajax上传图片

发布于2022-12-01 07:32     阅读(855)     评论(0)     点赞(19)     收藏(4)


我在 django 应用程序中遇到了问题。我有一个 ajax 函数可以将单个图像上传到模型,但到目前为止,我无法成功实现我的目标。我基本上实现的是我从 Ajax 获取文件,但是当我尝试在视图中的 Django 请求中发送它时,结果是 None 对象。让我发布一些代码更清楚:

HTML:

{% for question in questions %}
    <tr>
     <td>{{forloop.counter}}</td>
     <td>{{question.id}}</td>
     <td>{{question}}</td>
     <td>
      <a title="{% trans "Edit Question" %}" class="btn btn-warning btn-sm" href="{% url 'administration:edit_question' pk=question.id %}"><i class="fas fa-edit"></i></a>
      <a title="{% trans "See Details" %}" class="btn btn-primary btn-sm ms-3" href="{% url 'administration:question_details' pk=question.id %}" ><i class="fas fa-eye"></i></a>
      <a title="{% trans "Delete Question" %}" href="{% url 'administration:delete_question' pk=question.id %}" id="delete_question" class="btn btn-sm btn-danger ms-3"><i class="fas fa-trash"></i></a>
      <button title="{% trans "Add Image" %}" class="btn btn-sm btn-success ms-3" data-bs-toggle="modal" data-bs-target="#addImageModal{{question.id}}"><i class="fas fa-file-image"></i></button>
      {% if question.explanation %}
      <a title="{% trans "Edit Explanation" %}" href="{% url 'administration:edit_explanation' pk=question.explanation.id %}" class="btn btn-sm btn-info ms-3"><i class="fas fa-edit"></i></a>
      <button title="{% trans "Add Explanation Image" %}" data-bs-toggle="modal" data-bs-target="#addExplanationImageModal{{question.id}}" data-questionId="{{question.id}}" class="btn btn-sm btn-secondary explanationModals ms-3"><i class="fas fa-plus"></i></button>
      {% else %}
       <a title="{% trans "Add Explanation" %}" href="{% url 'administration:add_explanation' pk=question.id %}" class="btn btn-sm btn-info ms-3"><i class="fas fa-plus"></i></a>
       {% endif %}
      </td>
 {% include 'administration/modals/add_question_image_modal.html' %}
 {% include 'administration/modals/add_explanation_image_modal.html' %}
    </tr>
   {% endfor %}

模态:

<div class="modal fade" id="addExplanationImageModal{{question.id}}" tabindex="-1" role="dialog" aria-labelledby="addExplanationImageModalLabel" aria-modal="true" style="display: none;">
<div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">{% trans "Add Explanation Image to Explanation n°" %} {{question.explanation.id}}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <form action="" id="explanationImageForm{{question.id}}" enctype="multipart/form-data">
                {% csrf_token %}
                <div class="form-group">
                  <label>{% trans "Image" %}</label>
                  <input class="form-control" type="file" name="file" id="explanationPicFile{{question.id}}">
                </div>
                <button type="button" id="addExplanationImage{{question.id}}" class="btn btn-success mt-3"> {% trans "Add Image" %} </button>
                <button type="button" class="btn btn-danger mt-3" data-bs-dismiss="modal">{% trans "Close" %}</button>
            </form>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

脚本:

let explanationModals = [...document.getElementsByClassName('explanationModals')];
explanationModals.forEach((explanationModal) =>
explanationModal.addEventListener("click", (e) => {
    e.preventDefault();
  var questionId = explanationModal.getAttribute("data-questionId");
  
    $('#addExplanationImage'+questionId).on('click', function(e){
        var file = document.getElementById('explanationPicFile'+questionId).files[0]
    var data = new FormData();
    data.append('file', file);
    data.append('csrfmiddlewaretoken', csrftoken);
        $.ajax({
            type: 'POST',
            url: '/administration/add_ajax_question_explanation_image/' +questionId,
            enctype: 'multipart/form-data',
            data: data,
            cache: false, 
            processData: false,
            contentType: false,
            enctype: 'multipart/form-data',
            success: function(res){
                console.log(res)
                console.log(data.get('file'))
            }, 
            error: function(err){
                console.log(err)
            },
        })
    })
})

);

views.py

def add_ajax_question_explanation_image(request, pk):
    question = Question.objects.get(id=pk)
    explanation = Explanation.objects.get(question=question)
    if request.headers.get('x-requested-with') == 'XMLHttpRequest':
        file = request.FILES.get('file')
        image = ExplanationImage(image=file, explanation=explanation)
        image.save()
        return HttpResponse(image)

视图正确返回,但文件未在图像对象内部传递。如果我打印它返回的文件None


解决方案


暂无回答



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/1870631/f44f5794525e4459413a/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

19 0
收藏该文
已收藏

评论内容:(最多支持255个字符)