Django shopping cart example

560 views
Skip to first unread message

Janeskil1525

unread,
Oct 18, 2012, 4:11:23 PM10/18/12
to django...@googlegroups.com
Hi All


I found a nice shopping cart example for Django on Djangoresources called ajax_shop_basket . It works really nice apart from the javascript function
addProduct gets an 403 message´when it tries to post. I guess that's because of non existing csrf_token 
in that function. I have no clue how to add this to Javascript so any help or pointers a how to do or
where to look for info is deeply appreciated!


Thank you in advance !

Best Regards
Jan Eskilsson

Amyth Arora

unread,
Oct 20, 2012, 7:41:24 PM10/20/12
to django...@googlegroups.com
Try this

$(document).ajaxSend(function(event, xhr, settings) {
    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;
    }   
    function sameOrigin(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));
    }   
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }   

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }   
});


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/f_WMtxxERZoJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



--
Thanks & Regards
----------------------------

Amyth [Admin - Techstricks]
Email - aroras....@gmail.com, ad...@techstricks.com
Twitter - @mytharora
http://techstricks.com/
Reply all
Reply to author
Forward
0 new messages