Django与jquery-fileupload ui抛出错误"此字段是必需的。"

时间:2017-05-03 07:00:49

标签: jquery python django file-upload

我有一个Django项目功能上传文件进行分析。 我引用并移植了来自sigurdga/django-jquery-file-upload的UI部分,特别是上传表单和按钮,包括静态css,js文件和一些python脚本。

一切都已确定,但它只是一直告诉我"这个字段是必需的。"在"开始"单击按钮。

views.py

import json
from django.views.generic import CreateView, DeleteView, ListView
from django.views import View
from django.shortcuts import render
from django.http import HttpResponse
from .models import File
from .response import JSONResponse, response_mimetype
from .serialize import serialize

class FileCreateView(CreateView):
    model = File
    fields = "__all__"

    def form_valid(self, form):
        self.object = form.save()
        files = [serialize(self.object)]
        data = {'files': files}
        response = JSONResponse(data, mimetype=response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response

    def form_invalid(self, form):
        data = json.dumps(form.errors)
        return HttpResponse(content=data, status=400, content_type='application/json')

models.py

from django.db import models


class File(models.Model):
    file = models.FileField(upload_to="files")
    slug = models.SlugField(max_length=50, blank=True)

    def __str__(self):
        return self.file.name

    @models.permalink
    def get_absolute_url(self):
        return ('profiler-new', )

    def save(self, *args, **kwargs):
        self.slug = self.file.name
        super(File, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        """delete -- Remove to leave file."""
        self.file.delete(False)
        super(File, self).delete(*args, **kwargs)

urls.py

from django.conf.urls import url
from .views import Example, FileCreateView, FileDeleteView, FileListView

urlpatterns = [
    url(r'^new/$', FileCreateView.as_view(), name='profile-new'),
...

file_form.html

...
<div class="container" style="width: 100%">
    <!-- The file upload form used as target for the file upload widget -->
    <form id="fileupload" action="{% url 'profile-new' %}" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <!-- Redirect browsers with JavaScript disabled to the origin page -->

        <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
        <div class="row fileupload-buttonbar">
            <div class="col-lg-7">
...

我将 main.js 修改为:

/* global $, window */

$(function () {
    'use strict';

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: '/profiler/new/'
    });
...

当我测试上传功能并且javascript小部件有效时,我从[]获得request.FILES.getlist("files")并获得form

<tr><th><label for="id_file">File:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="file" name="file" required id="id_file" /></td></tr>
<tr><th><label for="id_slug">Slug:</label></th><td><input type="text" name="slug" maxlength="50" id="id_slug" /></td></tr>

Cloud有人帮我确定错误的关键并建议如何处理它?<​​/ p>

更新1

我将两个参数blank=True, null=True添加到FileField并抛出了另一个异常:ValueError: The 'file' attribute has no file associated with it.

1 个答案:

答案 0 :(得分:1)

在filefield的模型中输入blank = True和null = True