django - 尝试使用 django 和 dropzone/

标签 django django-views dropzone.js django-file-upload

我正在尝试将 dropzone.js 与 django 一起使用。

我正在关注有点过时的指南( https://amatellanes.wordpress.com/2013/11/05/dropzonejs-django-how-to-build-a-file-upload-form/ )

我强烈怀疑我的观点有问题。

def test(request):
    print "test view has been called"
    if request.method == 'POST':
        print "test request method is POST"
        form = UploadFileForm(request.POST, request.FILES)
        print request
        print request.FILES
        if form.is_valid():
            new_file = AttachedFiles(attachedfile=request.FILES['file'])
            new_file.save()
            id = new_file.pk
            print id
            print "test form valid"
            return HttpResponse(json.dumps({'id': id}), content_type="application/json")
       print "test form not valid"
   else:
       form = UploadFileForm()
   data = {'form': form}
   return render_to_response('mediamanager/test.html', data, context_instance=RequestContext(request))

我已经测试过使用 dropzone 代码提交给它
        <!-- IMPORTANT enctype attribute! -->
    <form id="my_dropzone" class="dropzone" action="/mediamanager/test/" method="post" enctype="multipart/form-data">
        {% csrf_token %}
     <button id="submit-all">
        Submit all files
    </button>
    </form>
    <script src="{% static 'dropzone/js/dropzone.js' %}"></script>
    <script type="text/javascript">
        Dropzone.options.myDropzone = {

            // Prevents Dropzone from uploading dropped files immediately
            autoProcessQueue : true,

            init : function() {
                var submitButton = document.querySelector("#submit-all")
                myDropzone = this;

                submitButton.addEventListener("click", function() {
                    myDropzone.processQueue();
                    // Tell Dropzone to process all queued files.
                });

                // You might want to show the submit button only when
                // files are dropped here:
                this.on("addedfile", function() {
                    // Show submit button here and/or inform user to click it.
                    console.log("blah")
                });
            }
        };
    </script>

和一个基本形式
<form action="{% url "test" %}" method="post" enctype="multipart/form-data">
  {% csrf_token %}
<input type="file" name="file" />
<input type="submit" value="Submit">
</form>

表格永远无效。
我正在按照建议使用模型形式
class UploadFileForm(forms.ModelForm):
    class Meta:
        model = AttachedFiles

最佳答案

您可以像处理任何其他多部分表单帖子一样处理 Dropzone 帖子。

这是我如何进行的:

@login_required
@usertype_required
def upload_picture(request, uid=None):
    """
    Photo upload / dropzone handler
    :param request:
    :param uid: Optional picture UID when re-uploading a file.
    :return:
    """
    form = PhotoUploadForm(request.POST, request.FILES or None)
    if form.is_valid():
        pic = request.FILES['file']
        # [...] Process whatever you do with that file there. I resize it, create thumbnails, etc.
        # Get an instance of picture model (defined below) 
        picture = ...         
        picture.file = pic
        picture.save()
        return HttpResponse('Image upload succeeded.')
    return HttpResponseBadRequest("Image upload form not valid.")

形式非常简单

class PhotoUploadForm(forms.Form):
    # Keep name to 'file' because that's what Dropzone is using
    file = forms.ImageField(required=True)

在您的模型中,您需要设置 upload_to:

class Picture(models.Model):
    [...]
    # Original
    file = models.ImageField(upload_to=get_upload_path)

这是我的上传路径构建器,但你可以放任何东西

def get_upload_path(instance, filename):
    """ creates unique-Path & filename for upload """
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (instance.p_uid, ext)
    d = datetime.date.today()
    username = instance.author.username

    #Create the directory structure
    return os.path.join(
        'userpics', username, d.strftime('%Y'), d.strftime('%m'), filename
    )

不要忘记 html 表单本身中的 csrf_token(我在它上面使用了一个 angularJS 指令,所以对你来说会有所不同)

<form action="{% url 'upload_picture' %}" class="dropzone" drop-zone>
    {% csrf_token %}
    <div class="fallback">
        <h3>Your browser is not supported.</h3>
        <strong>
            <a href="https://browser-update.org/update.html" target="_blank">Click here for instructions on how to update it.</a>
        </strong>
        <p>You can still try to upload your pictures through this form: </p>
        <p>
            <input name="file" type="file" multiple />
            <input type="submit" value="Upload" />
        </p>
     </div>
 </form>

关于django - 尝试使用 django 和 dropzone/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30077990/

相关文章:

python - ModelForm 的 save 方法中的 Django admin.py : save_model() is not called by model. save()

python - 异常值 : context must be a dict rather than WSGIRequest

python - 是否可以在另一个views.py方法中访问通过HTML表单提交、在预览页面中呈现的值

python - 错误 : "Cannot use None as a query value" When trying to paginate with ListView in Django

javascript - 确定 dropzone.js 中所有文件何时上传成功

python - 跳过 django FormWizard 上的步骤

python - DRF 测试 JSON 对象列表是否包含特定对象

javascript - safari 中的 reduxForm 输入文件返回未定义

python - django 命令找不到命令模块

javascript - 如何使用 Dropzone.js 在服务器错误响应后触发警报