通过jQuery /阿贾克斯邮报的ImageField提交表单(Django的形式)? [英] Submit form (django-form) with Imagefield via Jquery/Ajax Post?

查看:262
本文介绍了通过jQuery /阿贾克斯邮报的ImageField提交表单(Django的形式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林有一些问题提交表单(Django的形式)与使用jQuery / AJAX发表的ImageField。林又回到现场要求验证错误上的ImageField。

我一直在试图与附加FORMDATA但没有效果为止不同的解决方案。我是在正确的轨道?请点我在正确的方向。谢谢!

更新:我可以设置的ImageField所需=假,并没有得到验证错误,但我想需要的领域,它看起来像的形式仍然不提交的形象。

其基本功能是这样的:

  $(函数(){
    $('#imageupload')。在('点击',函数(){

        $('#对话框模式)的负载(上传/ #myform')。

        $('#对话框模式)。对话框({
              高度:550,
              宽度:280,
              模式:真正的,

              按钮:{
                    发送:函数(){
                        VAR对话框= $(本),
                            表= $('#MyForm的),
                            数据= form.serialize();

                    $('小康')删除();

                    $阿贾克斯({
                        网址:上传/',
                        数据:数据,
                        类型:'后',

                        成功:函数(响应){
                            RES = $ .parseJSON(响应);

                            如果(RES ['状态'] =='OK'){
                                警报('谢谢你!');
                                dialog.dialog(亲密);
                            }

                            否则,如果(RES ['状态'] =='坏'){
                                警报(请重试!);
                                删除资源['状态']
                                VAR错误=资源;

                                $每个(错误,功能(键,值){

                                    VAR ERR = $('<跨度>< / SPAN>',{
                                                    类:关闭,
                                                    文本:价值
                                            }),
                                        BR = $('< BR>< / BR>',{
                                            类:关闭,
                                        }),
                                        输入= $('#号_'+键).parent();

                                    br.appendTo(输入);

                                    err.appendTo(输入);

                                    err.css('色','红'),CSS('字号','10px的')。

                                });
                            }
                        }

                      });

                    }
                  }
            });


    });
})
 

表看起来是这样的,它是在一个孩子的HTML至极被装入一个jQuery对话框/模态对话框:

 <形式方法=邮报的id ='MyForm的'ENCTYPE =的multipart / form-data的>
    {%csrf_token%}
    < H1>上传< / H1>
    < P><标签=名与GT;名称:< /标签>< / P>
    < D​​IV CLASS =fieldWrapper>
    {{form.name}}
    < / DIV>
    < BR>
    &其中p为H.;&所述;标签=类型>类型:其中; /标签>&所述; / P>
    < D​​IV CLASS =fieldWrapper>
    {{form.type}}
    < / DIV>
    < BR>
    < P><标签=描述>简介:< /标签>< / P>
    < D​​IV CLASS =fieldWrapper>
    {{form.description}}
    < / DIV>
    < BR>
    < P><标签=图片>图片:LT; /标签>< / P>
    < D​​IV CLASS =fieldWrapper>
    {{form.picture}}
    < / DIV>
    < /形式GT;
 

解决方案

有一个已知的问题通过jQuery的AJAX文件上传。有<一href="http://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery/8244082#8244082">tons 的 =HTTP:/ /www.phpletter.com/Demo/AjaxFileUpload-Demo/相对=nofollow>和插件在那里,他们大多使用一个iframe 。但是,我认为 malsup的jQuery插件的形式提供了最简单他们全部,只有轻微修改您的code:

里添加此&LT; HEAD&GT; 标签:

 &LT;脚本SRC =htt​​p://malsup.github.com/jquery.form.js&GT;&LT; / SCRIPT&GT;
 

改中的code中的发送功能如下所示:

 按钮:{
    发送:函数(){
        $('小康')删除();
        VAR对话框= $(本),
            选项​​= {
                网址:上传/',
                键入:POST,
                成功:函数(响应){
                    //一切都在这里同
                    }
                };

        $('#MyForm的')ajaxSubmit会(选件)。

    }
  }
 

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

 的形式= UploadForm(request.POST,request.FILES)
 

P.S。最后一个音符 - 如前所述,这是一个已知的问题,并从malsup的解决方案使用一种叫 XMLHtt prequest 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 /阿贾克斯邮报的ImageField提交表单(Django的形式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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