Django - 保存表单值时出现Ajax错误

时间:2012-10-18 12:30:53

标签: django jquery django-views

我有一个编辑表单页面,用于编辑现有帖子。我想在此页面中添加预览链接。我想要的是什么;当我点击预览链接时,它必须;

  1. 获取表单元素的当前值并将其写入my Post_Preview模型。
  2. 然后,ajax函数必须重定向到我在视图和网址中定义的* show_preview *页面。
  3. 并且在show_preview页面(preview.html)中必须呈现它。 (形式 当前值)
  4. 这是必须的。这是我的代码:

    和我的编辑表单页面

    <form method="post" action="">
        {% csrf_token %}
        <input type="hidden" id="post_owner" value="{{ post.owner }}"/></td>
        <input type="hidden" id="post_id" value="{{ post.id }}"> </td>
    
                {{ form.title }}
                {{ form.body }}
    
        <a href="#" id="preview">Preview</a>
        <input type="submit" value="Save" style="cursor: pointer;"/>
    </form>
    

    ajax功能:

    $(function(){
    
        $('#preview').click(function() {
    
            var title = $('#id_title').val();
            var body = $('#id_body').val();
            var owner = $('#post_owner').val(); //hidden value at form page
            var id = $('#post_id').val();  //hidden value at form page
    
         var ajaxOptions = {
             type:'post',
             url : '/admin/post/save_preview/', //save_preview's url
             data : {
                 'title' : title,
                 'body'  : body,
                 'owner' : owner,
                 'id'    : id
             },
             success: function(){
                 window.open("/blog/"+owner+"/preview/"+id); //show_preview's url
             },
             error: function(){
                alert('There is an Error'); //this is what i see when click preview link.
             }
         };
           $.ajax(ajaxOptions);
    });
    });
    

    我的save_preview视图:

    def save_preview(request):
        title = request.POST['title']
        body = request.POST['body']
        owner = request.POST['owner']
        post_id = request.POST['id']
        try:
            preview = Post_Preview(id=post_id, title=title, body=body, owner=owner)
            preview.save()
        except:
            pass
        return HttpResponse(200)
    

    我的show_preview视图:

    def show_preview(request,post_id,username):
        preview = Post_Preview.objects.get(id=post_id)
    
        return render_to_response('preview.html',{'post': preview}, context_instance=RequestContext(request))
    

    我的相关网址:

    url(r'^admin/post/save_preview/', view='save_preview' ,name='save_preview'),
    url(r'^blog/(?P<username>[-\w]+)/preview/(?P<post_id>\d+)', view='show_preview', name='show_preview'),
    

    当我点击编辑表单页面上的预览链接时:它显示“有错误”错误;这是在ajax函数中定义的。

    谢谢你!

    编辑:在js文件中我的ajax函数之前有更多的代码(与django-ajax关系有关):

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');
    
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    function sameOrigin(url) {
        // test that a given url is a same-origin URL
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
                // Send the token to same-origin, relative URLs only.
                // Send the token only if the method warrants CSRF protection
                // Using the CSRFToken value acquired earlier
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
    

    编辑2:当我为save_preview添加try / except块时;我没有扔弹出错误页面。它被重定向到save_preview页面并抛出错误:

    Post_Preview matching query does not exist.
    
    156. preview = Post_Preview.objects.get(id=post_id)
    

1 个答案:

答案 0 :(得分:1)

您没有在$ .ajax中发送csrf令牌。