简体   繁体   English

csrf令牌丢失或不正确

[英]csrf token is missing or incorrect

followed a lot of the stuff recommended on StackOverflow. 跟着StackOverflow上推荐的很多东西。 Also I tried to put {% csrf_token %} in the html in various places but none seemed to work. 我也尝试在不同的地方将{%csrf_token%}放在html中,但似乎没有任何作用。 Any suggestions? 有什么建议么?

Here is my django templates input button 这是我的Django模板输入按钮

 <input id=saveWaypoints type=button value='Save your Location' disabled=disabled>

Which calls this javascript 哪个叫这个javascript

$('#saveWaypoints').click(function () {
                var waypointStrings = [];
                for (id in waypointByID) {
                    waypoint = waypointByID[id];
                    waypointStrings.push(id + ' ' + waypoint.lng + ' ' + waypoint.lat);
                };

                $.post("{% url 'waypoints-save' %}", {
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                    waypointsPayload: waypointStrings.join('\n')
                }, function (data) {
                    if (data.isOk) {
                        $('#saveWaypoints').attr('disabled', 'disabled');
                    } else {
                        alert(data.message);
                    }
                });
            });

My complete javascript code is 我完整的javascript代码是

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Maps | {% block title %}{% endblock %}</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
    <script>
        var map, marker, waypointByID = {};
        var currentObject;
        var map;
        var geocoder;

        function initialize() {
            map = new google.maps.Map(document.getElementById('map'), {
                zoom: 5,
                center: new google.maps.LatLng(41.879535, -87.624333),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            geocoder = new google.maps.Geocoder();


        }

        $(function () {

        });




        {% for waypoint in waypoints %}
        waypointByID[{{waypoint.id}}] = {
            name: "{{waypoint.name}}",
            lat: {{waypoint.geometry.y}},
            lng: {{waypoint.geometry.x}}
        };
        {% endfor %}






        var currentObject;



        $(document).ready(function () {
            function activateWaypoints() {
                // Add waypoint click handler
                $('.waypoint').each(function () {
                    $(this).click(function() {
                        var waypoint = waypointByID[this.id];
                        var center = new google.maps.LatLng(waypoint.lat, waypoint.lng);
                        currentObject = $(this);
                        if (marker) marker.setMap();
                        marker = new google.maps.Marker({map: map, position: center, draggable: true});
                        google.maps.event.addListener(marker, 'dragend', function() {
                            var position = marker.getPosition();
                            waypoint.lat = position.lat();
                            waypoint.lng = position.lng();
                            currentObject.html(waypoint.name +
                                ' (' + waypoint.lat +
                                ', ' + waypoint.lng + ')');
                            $('#saveWaypoints').removeAttr('disabled');
                        });
                        map.panTo(center);
                    }).hover(
                        function () {this.className = this.className.replace('OFF', 'ON');},
                        function () {this.className = this.className.replace('ON', 'OFF');}
                    );
                });
            }
            $('#saveWaypoints').click(function () {
                var waypointStrings = [];
                for (id in waypointByID) {
                    waypoint = waypointByID[id];
                    waypointStrings.push(id + ' ' + waypoint.lng + ' ' + waypoint.lat);
                };

                $.post("{% url 'waypoints-save' %}", {
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                    waypointsPayload: waypointStrings.join('\n')
                }, function (data) {
                    if (data.isOk) {
                        $('#saveWaypoints').attr('disabled', 'disabled');
                    } else {
                        alert(data.message);
                    }
                });
            });
            activateWaypoints();
        });
    </script>

    <style>
        body {font-family: sans-serif}
        #map {width: 1000px; height: 500px}
        #waypoints {overflow: auto; width: 500px; height: 100px}
        .linkOFF {color: darkblue}
        .linkON {color: white; background-color: darkblue}
    </style>


    </head>

    <body>
        <div id="nav">
            <a href="/">home</a> |
        {% if user.is_authenticated %}
            welcome {{ user.username }}
            (<a href="/logout">logout</a>)
        {% else %}
            <a href="/login/">login</a> |
            <a href="/register/">register</a>
        {% endif %}
        </div>
        <h1>{% block head %}{% endblock %}</h1>
        {% block content %}{% endblock %}
    </body>

    <body onload='initialize()'>
        <div id=map></div>
        <div id=waypoints>
            {% for waypoint in waypoints %}
                <div id={{waypoint.id}} class='waypoint linkOFF'>
                    {{waypoint.name}} ({{waypoint.geometry.y}}, {{waypoint.geometry.x}})
                </div>
            {% endfor %}

        </div>
        <input id=saveWaypoints type=button value='Save your Location' disabled=disabled>
    </body>

</html>

My views.py is 我的views.py是

def save(request):
    'Save waypoints'


    for waypointString in request.POST.get('waypointsPayload', '').splitlines():
        waypointID, waypointX, waypointY = waypointString.split()
        waypoint = Waypoint.objects.get(id=int(waypointID))
        waypoint.geometry.set_x(float(waypointX))
        waypoint.geometry.set_y(float(waypointY))
        waypoint.save()
    return HttpResponse(simplejson.dumps(dict(isOk=1)), mimetype='application/json')

Any suggestions please . 任何建议请。 Thanks 谢谢

This worked for me: 这为我工作:

$.post("{% url 'waypoints-save' %}", {
  'csrfmiddlewaretoken': '{{ csrf_token }}',
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM