0

我有一个编辑现有帖子的编辑表单页面。我想在这个页面上放一个预览链接。我想要的是;当我单击预览链接时,它必须;

  1. 获取表单元素的当前值并将它们写入我的 Post_Preview 模型。
  2. 然后,ajax 函数必须重定向到我在视图和 URL 中定义的 *show_preview* 页面。
  3. 并且必须在 show_preview 页面 (preview.html) 中呈现它。(表单的当前值)

这就是它必须的工作方式。这是我的代码:

和我的编辑表单页面:

<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)
4

1 回答 1

1

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

于 2012-10-18T12:46:00.573 回答