简体   繁体   中英

Getting 403 Forbidden error even after providing csrf token

The below is my Ajax POST request

This is on template

<script type="text/javascript">
    function submit_vote(){
        callback = function(data){
            alert(data.message);
        };

        $.post("{{request.get_full_path}}vote",{
            "rating" : $('#{{hash_id}}').raty('score')
        }, callback, "json");
    }
</script>

<div class="rating" id="{{hash_id}}" onclick="submit_vote()"></div>

On the views, here is it

This is the view that renders the template in which Ajax script exists

@csrf_protect
def show_rating(request, **kwargs):
    ....
    ....
    return render_to_response("rating.html",
                context,
                context_instance = RequestContext(request))

This is the view that takes POST Request

@login_required
@csrf_protect
def submit_vote(request, **kwargs):
    if not request.method == "POST":
        raise Http404

    ...
    ...

    data = {"error" : False, "message" : "Thanks"}
    data = simplejson.dumps(data)
    return HttpResponse(data, mimetype="application/javascript")

Upon trying the above code, I am getting 403 Forbidden Error.. By using django documentation, I added another script to the existing code (at the top)

<script type="text/javascript">
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);
        }
    }
});
</script>

Now I am getting

Uncaught ReferenceError: csrftoken is not defined 

error..

how to fix it? actually, I am not aware of Ajax and Jquery and JS.. just trying to build a simple request out of tutorials on the web!

You can just send a csrfmiddlewaretoken in your post request and it should be fixed.

$.post("{{request.get_full_path}}vote",{
        "rating" : $('#{{hash_id}}').raty('score'),
        "csrfmiddlewaretoken": {{csrf_token}},
    }, callback, "json");

You don't need any other script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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