简体   繁体   中英

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

I have a Django project features uploading file for analysis. 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.

Everything was set, but it just keep telling me "This field is required." after "Start" button was clicked.

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

And I modified the main.js as:

/* 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:

<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

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放入文件字段的模型中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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