Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用django注释:用ajax发送表单,用新项呈现div,然后重新启动_Django_Django Templates_Django Csrf - Fatal编程技术网

用django注释:用ajax发送表单,用新项呈现div,然后重新启动

用django注释:用ajax发送表单,用新项呈现div,然后重新启动,django,django-templates,django-csrf,Django,Django Templates,Django Csrf,我想创建一个简单的annotation web应用程序,我想让用户看到一个项目,用一个简单的单选表单进行注释,提交表单,查看下一个项目,进行注释,等等 我正在使用Django,但无法使其正常工作。问题是,它适用于第一次提交,但第二次提交时会出现错误: Forbidden (403) CSRF verification failed. Request aborted. 这是我测试的内容: 名为anotar的应用程序,具有以下url.py: app_name = 'anotar' urlpatte

我想创建一个简单的annotation web应用程序,我想让用户看到一个项目,用一个简单的单选表单进行注释,提交表单,查看下一个项目,进行注释,等等

我正在使用Django,但无法使其正常工作。问题是,它适用于第一次提交,但第二次提交时会出现错误:

Forbidden (403)
CSRF verification failed. Request aborted.
这是我测试的内容:

名为
anotar
的应用程序,具有以下
url.py

app_name = 'anotar'
urlpatterns = [
    path('',views.dashboard,name = 'dashboard'),
    ]
def dashboard(request):

    template = 'anotar/dashboard.html'
    tweet_id = '1323646485200850945'

    if request.is_ajax():
        print("AJAX")
        # I will save the anotation here and pass the another id for new anotation
        template = 'anotar/tweet.html'
        tweet_id = '1324423455002005505'
        html = render_to_string(template,{'tweet_id':tweet_id})
        return JsonResponse({'html':html},safe=False)

    return render(request, template, {'tweet_id':tweet_id})
视图.py中

app_name = 'anotar'
urlpatterns = [
    path('',views.dashboard,name = 'dashboard'),
    ]
def dashboard(request):

    template = 'anotar/dashboard.html'
    tweet_id = '1323646485200850945'

    if request.is_ajax():
        print("AJAX")
        # I will save the anotation here and pass the another id for new anotation
        template = 'anotar/tweet.html'
        tweet_id = '1324423455002005505'
        html = render_to_string(template,{'tweet_id':tweet_id})
        return JsonResponse({'html':html},safe=False)

    return render(request, template, {'tweet_id':tweet_id})
然后,
dashboard.html

{% extends 'base.html' %}
{% load static %}

<div id="teste-include">
  {% include "anotar/tweet.html" %}
</div>


{% block domready %}

$('#post-form').on('submit', function(event){
    event.preventDefault();
    console.log("form submitted!")  // sanity check
    save_anotation();
});


function save_anotation() {
    console.log("create post is working!") // sanity check
    console.log($('.form-check-input:checked').val())
    $.ajax({
        url :'{% url "anotar:dashboard" %}', // the endpoint
        type : "POST", // http method
        data : { option : $('.form-check-input:checked').val() }, // data sent with the post request
        // handle a successful response
        success : function(data) {
            $('#teste-include').html(data.html);
        },
        error: function(){
          console.log("Error!") // sanity check
        },

    });
};

{% endblock %}
{{tweet_id}}

<form action='{% url "anotar:dashboard" %}' method="POST" id="post-form">
    {% csrf_token %}
    <fieldset>
        <fieldset class="form-group">
            <div class="form-check">
                <label class="form-check-label">
                    <input type="radio" class="form-check-input" name="optionsRadios" id="optionsRadios1" value="positivo">
                    Positivo
                </label>
            </div>
            <div class="form-check">
                <label class="form-check-label">
                    <input type="radio" class="form-check-input" name="optionsRadios" id="optionsRadios2" value="negativo" >
                    Negativo
                </label>
            </div>
        </fieldset>
        <button type="submit" class="btn btn-primary btn-lg" >Submit</button>
    </fieldset>
</form>
base.html
中,我有:

<script>

// using jQuery
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));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});



  $(document).ready(function(){
    {% block domready %}
    {% endblock %}
  });
</script>

//使用jQuery
函数getCookie(名称){
var-cookieValue=null;
if(document.cookie&&document.cookie!=''){
var cookies=document.cookie.split(“;”);
对于(变量i=0;i