使用 jQuery 表单插件提交时 Django 表单出现问题

发布于 2024-08-14 01:31:13 字数 2635 浏览 4 评论 0原文

当使用 jQuery 表单插件提交表单时,目标视图收到的请求与以标准方式(没有 JavaScript)提交表单时收到的请求不同,并且我的 Django 模板未按预期呈现。 当以标准方式提交时,模板会呈现表单错误(“form.[field_name].errors”),而通过 javascript 提交时则不会。 使用 javascript 提交,如何获得允许像使用标准提交一样呈现模板的请求? 下面显示了两种情况下收到的请求对象之间的代码和差异。

谢谢 jul

javascript 代码:

var is_geocoded = false;
var interval;

$(function(){

    $("#submit").click(function() {  
        var options = { 
            beforeSubmit:  getPosition,  // pre-submit callback 
            success:       showResponse  // post-submit callback       
        }; 

        // bind form using 'ajaxForm' 
        $('#addresto').ajaxForm(options); 
    });  

});

function getPosition() {

    var geocoder =  new GClientGeocoder();
    var country = $("#id_country").val();
    var city = $("#id_city").val();
    var postal_code = $("#id_postal_code").val();
    var street_number = $("#id_street_number").val();
    var street = $("#id_street").val();
    var address = street_number+", "+street+", "+postal_code+", "+city+", "+country;

    geocoder.getLatLng( address, function(point) {

        if (point) {

            $("#id_latitude").val(point.lat())
            $("#id_longitude").val(point.lng())
            is_geocoded = true;
        } else {
            is_geocoded = true;
        }
    });

    interval = setInterval("doSubmit()", 500);

    return false;
}

function doSubmit() {

    if (is_geocoded) {
        $("#addresto").ajaxSubmit();
        clearInterval(interval);
    }
}

Django 模板代码:

<form id="addresto" action="" method="POST">

<p><label for="id_name">Name:</label>{{form.name.errors}} {{ form.name }} </p>
<p><label for="id_country">Country:</label>{{form.country.errors}} {{ form.country }} </p>

<!-- more stuff -->

<p style="clear: both;"><input type="Submit" id="submit" value="Submit" /></p>
</form>

这是使用标准提交和使用 javascript 提交视图收到的请求之间的区别:

xxx@xxx:~$ diff javascript_submit standard_submit 
7c7
<  'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=UTF-8',
---
>  'CONTENT_TYPE': 'application/x-www-form-urlencoded',
24c24
<  'HTTP_ACCEPT': '*/*',
---
>  'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
28d27
<  'HTTP_CACHE_CONTROL': 'no-cache',
33d31
<  'HTTP_PRAGMA': 'no-cache',
36d33
<  'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest',
70c67
<  'wsgi.input': <socket._fileobject object at 0x891d064>,
---
>  'wsgi.input': <socket._fileobject object at 0x898b09c>,

when submitting my form using jQuery form plugin, the request received by the target view is different than that received when the form is submitted in the standard way (with no javascript), and my Django template does not render as expected.
When submitted in the standard way, the template renders the form errors (the "form.[field_name].errors), while it doesn't when submitted via javascript.
Using the javascript submit, how can I get a request allowing to render the template as it does using the standard submit?
The code and the diff between the request objects received in both cases are shown below.

thanks
jul

javascript code:

var is_geocoded = false;
var interval;

$(function(){

    $("#submit").click(function() {  
        var options = { 
            beforeSubmit:  getPosition,  // pre-submit callback 
            success:       showResponse  // post-submit callback       
        }; 

        // bind form using 'ajaxForm' 
        $('#addresto').ajaxForm(options); 
    });  

});

function getPosition() {

    var geocoder =  new GClientGeocoder();
    var country = $("#id_country").val();
    var city = $("#id_city").val();
    var postal_code = $("#id_postal_code").val();
    var street_number = $("#id_street_number").val();
    var street = $("#id_street").val();
    var address = street_number+", "+street+", "+postal_code+", "+city+", "+country;

    geocoder.getLatLng( address, function(point) {

        if (point) {

            $("#id_latitude").val(point.lat())
            $("#id_longitude").val(point.lng())
            is_geocoded = true;
        } else {
            is_geocoded = true;
        }
    });

    interval = setInterval("doSubmit()", 500);

    return false;
}

function doSubmit() {

    if (is_geocoded) {
        $("#addresto").ajaxSubmit();
        clearInterval(interval);
    }
}

Django template code:

<form id="addresto" action="" method="POST">

<p><label for="id_name">Name:</label>{{form.name.errors}} {{ form.name }} </p>
<p><label for="id_country">Country:</label>{{form.country.errors}} {{ form.country }} </p>

<!-- more stuff -->

<p style="clear: both;"><input type="Submit" id="submit" value="Submit" /></p>
</form>

Here's the difference between the requests received by the view with standard submit and with javascript submit:

xxx@xxx:~$ diff javascript_submit standard_submit 
7c7
<  'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=UTF-8',
---
>  'CONTENT_TYPE': 'application/x-www-form-urlencoded',
24c24
<  'HTTP_ACCEPT': '*/*',
---
>  'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
28d27
<  'HTTP_CACHE_CONTROL': 'no-cache',
33d31
<  'HTTP_PRAGMA': 'no-cache',
36d33
<  'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest',
70c67
<  'wsgi.input': <socket._fileobject object at 0x891d064>,
---
>  'wsgi.input': <socket._fileobject object at 0x898b09c>,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

束缚m 2024-08-21 01:31:13

通过ajax提交时不会出现错误的原因是您没有刷新页面。

您需要将 json 或 xml 传递回您的 javascript,并以这种方式将错误插入到页面中。

您也可以将表单渲染为 html 的 blob 并覆盖页面上的当前表单(但这有点复杂并且效率不高)

基本上我会推荐仅使用 django 的 request.is_ajax() 方法判断表单是否使用ajax提交,并针对ajax请求返回json

The reason the errors do not appear when you submit via ajax is that you aren't refreshing the page.

You'll need to pass json, or xml back to your javascript and insert the errors in to the page that way.

You could also just render the form to a blob of html and overwrite the current form on the page (but this is a little more complicated and isn't as efficient)

basically I would reccomende just using django's request.is_ajax() method to determine if the form is being submitted with ajax, and return json for ajax requests

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文