Thursday, December 22, 2011

Django POST csrf

Another trouble I ran into, but was solved very quickly thanks to Google and stackoverflow.

Django gives a HTTP forbidden error on ajax POST request, if the following Jquery code is not included, ie. if the POST request does not include the csrf token. The following snippet I found in stackoverflow, gets the token from the cookie.

Thanks to Jakub

$.ajaxSetup({ 
     beforeSend: function(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;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     } });


Friday, December 16, 2011

Some of my Django errors I faced and solved

This post is practically written for my sake alone - so that I'll know what to do later, if I face the same issues again.

Well here I go,

  • "django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2":  In django 1.3.1 settings.py file, if the database backed for Postgresql is simply given as 'postgresql' instead of postgresql_psycopg2, django simple gives the error as psycopg module not found. 

  • "django error no module named messages": If you install Ubuntu 10.04's django version, well I have to confess that i never updated, it was a fresh vm, and straightway run your django app, it throws this. Download and install the latest django version. Solved.

  • "django psycopg2.OperationalError: FATAL:  Ident authentication failed for user": Another classy misleading error. Just add 'localhost' in settings.py HOST, even though the helpful comment asks you to just leave it empty.

I LOVE DJANGO!!! This post is just to help another poor soul like me hunting in google and stackoverflow.