【问题标题】:How to receive uploaded file from the inlined form in django?如何从 django 中的内联表单接收上传的文件?
【发布时间】:2011-01-12 03:50:56
【问题描述】:

我正在尝试在 django 管理面板中创建一个“酷”的图像上传界面。问题是我使用内联接口上传图片实例,但我使用 jQuery Ajax 表单上传图片,所以我需要创建另一个表单来上传。现在 django 视图功能无法从这个表单接收 request.FILES,因为我没有使用 django.forms 创建它并且可以'不在视图函数中指定需要使用哪种形式。所以我不能覆盖内联接口的标准视图函数,也不能使用 django.forms 重新创建这个表单。所以这段代码似乎不起作用:

我的表格:

<form id="uploadForm" enctype="multipart/form-data" method="post" action="upload_picture/">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
</form>

我的视图功能:

def upload_picture(request):
    if request.method == 'POST':
        save_original(request.FILES['file'])
    return HttpResponseRedirect('admin/edit_inline/picture_editor.html')

也许我应该让它完全不同?

【问题讨论】:

  • 请注意,HttpResponseRedirect 应该使用绝对路径或完全限定的 URL 构造,而不是像您的相对路径。 HttpResponseRedirect('/admin/edit_inline/picture_editor.html') 应该会更好。

标签: python django forms image upload


【解决方案1】:

request.FILES 应该适用于该手工制作的表格。除了添加 id="id_file" 之外,Django 对该字段没有任何不同。我相当肯定你没有 id 不会干扰到 request.FILES 的转移。

In [5]: from django import forms

In [6]: class GenericFileForm(forms.Form):
   ...:         file = forms.FileField()
   ...: 

In [7]: g = GenericFileForm()

In [8]: print g
<tr><th><label for="id_file">File:</label></th><td><input type="file" name="file" id="id_file" /></td></tr>

【讨论】:

    【解决方案2】:

    我测试了这段代码,文件上传得很好。你能展示你用来构建表单的 jquery 吗?

    谢谢。

    【讨论】:

      【解决方案3】:

      我建议使用生成表单的模板片段,但也可以单独生成并发送到 jquery。这保留了 CSRF 令牌并允许您正确解析带有表单的文件

      例如你会使用:

      $.ajax({
          url: "/uploadPicture?JustForm",
          dataType: ($.browser.msie) ? "text" : "html",
          success: function(data){
              // Put the form contained in data onto the page (it's a string)
              $("formContainer").innerHtml(data)
          }
      });
      

      然后让您的视图直接返回您的表单

      def upload_picture(request):
          if request.GET.has_key('JustForm'):
              return YourFormObject.as_html() <- will include CSRF tags for compat with 1.2
          if request.method == 'POST':
              save_original(request.FILES['file'])
          return HttpResponseRedirect('admin/edit_inline/picture_editor.html')
      

      (忽略明显的错误,像伪代码一样对待)

      【讨论】:

        【解决方案4】:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-19
          • 2022-01-19
          • 2010-12-15
          • 2017-03-11
          • 2012-09-30
          • 1970-01-01
          • 1970-01-01
          • 2020-11-05
          相关资源
          最近更新 更多