python - django imagefield上传总是提示没有选择文件

标签 python django

我尝试通过以下方式创建个人资料图片上传字段:

class SignUpForm(forms.Form):
    username = forms.CharField(max_length=30, \
        error_messages = {'required': 'Need a username'})
    email = forms.EmailField(max_length=30, \
        error_messages = {'required': 'Need an email', 'invalid': 'Email is invalid'})
    profile_image = forms.ImageField(error_messages = {'required': 'Please select a profile image'})

并在views.py中加载数据:

  if request.method != 'POST':
    return HttpResponseServerError("Only POST requests allowed.")
  form = SignUpForm(request.POST, request.FILES)
  logger.info(request.FILES) # this always prints empty '{}'

形式为:

form(enctype="multipart/form-data", method='post')
      label(for='username') Username
      input#name(name='username', type='text')
      label(for='email') Email
      input#email(name='email', type='email')
      label(for='profile_image') Profile Image
      input#profile_image(name='profile_image', type='file')

我提交数据的方式是在js中:

$('form').submit(function(e){
  e.preventDefault();
  $("#signup-errors").hide();
  var form = $(e.target);
  var post = $.post('/user/create/', form.serialize(), redirectIfSuccess);
  post.fail(function(xhr, ajaxOptions, thrownError) {
    $("#signup-errors").html(xhr.getResponseHeader("errors")).show();
  });
});

有人可以提示我可能出了什么问题吗?我已经搜索并按照步骤操作,但文件从未通过...:(

谢谢!

最佳答案

根据您的更新,问题在于您正在使用 AJAX。

异步上传文件并不“容易”。 HTLM5 支持它,但并非所有浏览器都支持 - 您绝对还不能依赖此方法。

How can I upload files asynchronously?

我建议完成这项工作的方法是查看一些 ajax 文件上传插件(使用 iframe 或 flash)并使用他们的 API 来执行 POST。

http://blueimp.github.io/jQuery-File-Upload/

关于python - django imagefield上传总是提示没有选择文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076904/

相关文章:

python - 如何从包含列表的 Pandas 列中进行一次热编码?

python - 为什么 django queryset.extra() 抛出 OperationalError : (1242, 'Subquery returns more than 1 row' )?

python - Django 模块对象不可迭代

python - Django 应用程序的 Cython : would it work?

python - 如何在 keras 生成器中使用 numpy memmap 不超过 RAM 内存?

python - Jupyter Notebooks 使用 Matplotlib 打印出波浪形、扭曲的图形

python - 清理难看的所见即所得 HTML 代码? Python 或 *nix 实用程序

python - 在 Python 中查询时 MySQL 特殊字符丢失。 (但可以与 Django 一起使用。)

python - 正确使用 Django Mixins

python - 从 DataFrame 中的时间格式数据中删除小数秒