使用Ajax更新Django Filefield [英] Update a Django Filefield with Ajax

查看:120
本文介绍了使用Ajax更新Django Filefield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Ajax更新现有对象的FileField.在浏览器中创建了一个wav blob,我试图通过将其附加到FormData实例中来传递它:

I'm trying to update an existing objects' FileField with Ajax. A wav blob is created in the browser, and I'm trying to pass it by appending it to a FormData instance:

var data = new FormData();
            data.append('sound', blob);


$.ajax({
            url: "{% url 'posts:update_audio' instance.pk %}",
            type: 'POST',
            data: data,   
            cache: false,
            processData: false,
            contentType: false,
            success: function(data) {
              alert('success');
                }
            });
            return false;
            }

我将pk通过url传递到视图,因为(如果我错了,请更正我),但是我认为这是指定要更新的正确对象的路径的方法.这是视图:

I'm passing the pk through the url to the view, because (correct me if I'm wrong) but I think thats the way to specify the path to the correct objectt to be updated. Here is the view:

def update_audio(request,pk):
    form = UpdateAudio(request.POST or None, request.POST or None)
    if request.method == 'POST':


        if form.is_valid():
            instance = form.save(commit=False)      
            instance.save()


    return HttpResponseRedirect('/')

我就像对待提交表单的其他任何视图一样.我对应该如何更新特定对象有些困惑,这使我想到了一个问题:我是否应该为此使用特殊的视图,例如UpdateView?如果是这样,我该如何实施?如果没有,谁知道我要去哪里错了?我目前在尝试提交表单时仅收到内部服务器错误500.

Which I just treated like any other view which submits a form. I'm a bit confused about how this is supposed to update the specific object, which leads me to my question: Should I be using a special view for this, like UpdateView? If so, how can I implement it? If not, anyone know where I'm going wrong? I'm currently just getting an internal server error 500 when I try and submit the form.

推荐答案

将表单更改为此

instance = get_object_or_404(MyModel, id=pk)
form = MyUpdateAudioForm(request.POST or None,request.FILES, instance=instance)

和ajax网址

url: "{% url 'posts:update_audio' pk=instance.pk %}",

这篇关于使用Ajax更新Django Filefield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆