简体   繁体   English

带有jquery-fileupload ui的Django引发错误,显示“此字段是必需的。”

[英]Django with jquery-fileupload ui throws error with “This field is required.”

I have a Django project features uploading file for analysis. 我有一个Django项目功能,上载文件进行分析。 I reference and transplant the UI part from sigurdga/django-jquery-file-upload , specifically, the upload form and buttons, including the static css, js files and some of python scripts. 我从sigurdga / django-jquery-file-upload引用并移植了UI部分,尤其是上传表单和按钮,包括静态css,js文件和一些python脚本。

Everything was set, but it just keep telling me "This field is required." 一切都设置好了,但是它一直告诉我“此字段是必需的”。 after "Start" button was clicked. 单击“开始”按钮后。

views.py 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 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 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 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">
...

And I modified the main.js as: 我将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/'
    });
...

When I tested the upload function and the javascript widget works, I got [] from request.FILES.getlist("files") and got form as: 当我测试了上传功能并且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 anyone help me identify the key to the bug and suggest how to deal with it? 云中的任何人都可以帮助我确定该错误的关键并提出如何处理该错误的建议?

Update 1 更新1

I'v add the two parameters blank=True, null=True to the FileField and another exception was thrown: ValueError: The 'file' attribute has no file associated with it. 我将两个参数blank=True, null=True到FileField并引发了另一个异常: ValueError: The 'file' attribute has no file associated with it.

将blank = True和null = True放入文件字段的模型中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM