通过Jquery / Ajax Post通过Imagefield提交表单(django-form)? [英] Submit form (django-form) with Imagefield via Jquery/Ajax Post?

查看:233
本文介绍了通过Jquery / Ajax Post通过Imagefield提交表单(django-form)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Jquery / ajax POST提交带有imagefield的表单(Django-form)有一些问题。我在imagefield上恢复Field required验证错误。



我一直在尝试不同的解决方案,并附加了formData,但迄今没有任何结果。我在正确的轨道上吗?请指出正确的方向。谢谢!



更新:我可以将imagefield设置为required = false并且不会得到验证错误,但是我希望该字段是必需的,它似乎仍然是表单不提交图像..



基本功能如下所示:

  $(function(){
$('#imageupload')。on('click',function(){

$('#dialog-modal')。加载('upload / #myform');

$('#dialog-modal')。对话框({
height:550,
width:280,
modal:true,

按钮:{
发送:function(){
var dialog = $(this),
form = $('#myform' )
data = form.serialize();

$('。off')remove();

$ .ajax({
url:'upload /',
data:data,
type:'post',

success:function(response){
res = $ .parseJSON(response);

if(res ['status'] =='OK'){
alert('Thank you!');
dialog.dialog('close');
}

else if(res ['status'] =='bad'){
alert('Please try again!');
删除res ['status']
var errors = res;

$ .each(errors,function(key,value){

var err = $('< span>< / span>',{
'class':'off',
'text':value
}),
br = $('< br>< / br>',{
'class':'off',
}),
input = $('#id _'+ key).parent();

br.appendTo(input);

err.appendTo(input);

err.css('color','red')css('font-size','10px');

});
}
}

});

}
}
});


});
})

表单看起来像这样,它是在一个孩子html加载到jquery对话框/模式框:

 < form method =postid ='myform'enctype =multipart / form-数据> 
{%csrf_token%}
< h1>上传< / h1>
< p>< label for =name>名称:< / label>< / p>
< div class =fieldWrapper>
{{form.name}}
< / div>
< br>
< p>< label for =type>类型:< / label>< / p>
< div class =fieldWrapper>
{{form.type}}
< / div>
< br>
< p>< label for =description>说明:< / label>< / p>
< div class =fieldWrapper>
{{form.description}}
< / div>
< br>
< p>< label for =picture>图片:< / label>< / p>
< div class =fieldWrapper>
{{form.picture}}
< / div>
< / form>


解决方案

通过jQuery ajax有一个已知的文件上传问题。有 < a href =http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/ =nofollow noreferrer>解决方案 和插件 在那里,大多数使用一个iframe 。不过,我认为 malsup jQuery表单插件提供了最简单的一切,只需稍作修改到你的代码:



在里面添加< head> 标签:

 < script src =http://malsup.github.com/jquery.form.js>< / script> 

更改发送函数中的代码,如所以:

 按钮:{
发送:function(){
$('。off' 。去掉();
var dialog = $(this),
options = {
url:'upload /',
type:'POST',
success:function(response) {
//这里的一切都是一样的
}
};

$('#myform')。ajaxSubmit(options);

}
}

当然,在服务器上 - 您需要确保遵循说明从关于如何将文件绑定到表单的文档。对于最基本的用法,它通常归结为:

  form = UploadForm(request.POST,request.FILES)

ps一个最后一个注释 - 如上所述,这是一个已知的问题,malsup的解决方案使用了一些名为 XMLHttpRequest Level 2 。它只是一个较新的API,为AJAX请求提供更多功能,如文件上传,传送进度信息和发送表单数据的功能。我的观点是,旧的浏览器不支持它,所以请记住,如果你想要传统浏览器 - 用户使用您的网站,您需要找到一个替代方案。


Im having some problems submitting a form (Django-form) with a imagefield with Jquery/ajax POST. Im getting back "Field required" validation errors on the imagefield..

I been trying different solutions with appending formData but with no results so far. Am i on the right track? Please point me in the right direction. Thank you!

Update: I can set the imagefield to required=false and not get the validation error but i want the field to be required and it seems like the form still doesn't submit the image..

The basic function looks like this:

$(function() {
    $('#imageupload').on('click', function() { 

        $('#dialog-modal').load('upload/ #myform');

        $('#dialog-modal').dialog({
              height: 550,
              width: 280,
              modal: true,

              buttons: {
                    Send: function() { 
                        var dialog = $(this), 
                            form = $('#myform'),
                            data = form.serialize();

                    $('.off').remove(); 

                    $.ajax({ 
                        url: 'upload/',
                        data: data,
                        type: 'post',

                        success: function(response) {
                            res = $.parseJSON(response);

                            if (res['status'] == 'OK') {
                                alert('Thank you!'); 
                                dialog.dialog('close'); 
                            }

                            else if (res['status'] == 'bad') {
                                alert('Please try again!');
                                delete res['status'] 
                                var errors = res;

                                $.each(errors, function(key, value) {

                                    var err = $('<span></span>', {
                                                    'class': 'off',
                                                    'text': value
                                            }),
                                        br = $('<br></br>', {
                                            'class': 'off',
                                        }),
                                        input = $('#id_'+key).parent(); 

                                    br.appendTo(input);

                                    err.appendTo(input);

                                    err.css('color', 'red').css('font-size', '10px');

                                });
                            }
                        }

                      });

                    }
                  }
            });


    });
})

Form looks like this, it's in a child html wich is loaded into a jquery dialog/modal box:

    <form method="post" id='myform' enctype="multipart/form-data">
    {% csrf_token %}
    <h1> Upload </h1>
    <p><label for="name">Name:</label></p>
    <div class="fieldWrapper">
    {{ form.name }}
    </div>  
    <br>
    <p><label for="type">Type:</label></p> 
    <div class="fieldWrapper">                
    {{ form.type }}
    </div> 
    <br>
    <p><label for="description">Description:</label></p>  
    <div class="fieldWrapper">
    {{ form.description }}
    </div>  
    <br>  
    <p><label for="picture">Picture:</label></p> 
    <div class="fieldWrapper">                
    {{ form.picture }}
    </div> 
    </form>

解决方案

There's a known issue with file uploads through jQuery ajax. There are tons of solutions and plugins out there, most of them using an iframe. However, I think the malsup jQuery form plugin provides the easiest of them all, with only a slight modification to your code:

add this inside <head> tag:

<script src="http://malsup.github.com/jquery.form.js"></script> 

change the code within the Send function like so:

buttons: {
    Send: function() { 
        $('.off').remove();
        var dialog = $(this),
            options = {
                url: 'upload/',
                type: 'POST',
                success: function(response) {
                    // everything the same in here
                    }
                };

        $('#myform').ajaxSubmit(options);

    }
  }

Of course, on the server-side you need to make sure to follow the instructions from the documentation on how to bind the files to your form. For the most basic usage, it generally boils down to this:

form = UploadForm(request.POST, request.FILES)

p.s. one final note - as mentioned, it's a known issue, and the solution from malsup uses something called XMLHttpRequest Level 2. It's simply a newer API which provides more functionality to AJAX requests like file uploads, transfer progress information and the ability to send form data. My point being, older browsers don't support it, so bare in mind that if you want legacy-browser-users to make use of your site, you'll need to find an alternative.

这篇关于通过Jquery / Ajax Post通过Imagefield提交表单(django-form)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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