我有一个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 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/'
});
...
当我测试上传函数和JavaScript小部件有效时,我从request.FILES.getlist("files")
获得[]
,并获得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>
云有人帮助我确定错误的钥匙并建议如何处理?
更新1
i'v将两个参数 blank=True, null=True
添加到文件场,并抛出了另一个例外: ValueError: The 'file' attribute has no file associated with it.
put black = true and null = filefeel