Friday, December 26, 2014

How to make Ajax calls from jquery client side to django view

Problem - We need to make Ajax call from client side browser to the server posting some data. Instead of posting the whole form to the server we need to use ajax to post only the required data back to the server. The problem arises in how to provide URL parameter for the post call which includes the server root and the app route as well.

Solution - 

  • Let the form include the csrf token as provided by django framework by placing {% csrf_token %}
  • The javascript function that will make the required call at :

          var host = document.location.host; // host + port
          var protocol = document.location.protocol;
          var sr_origin = '//' + host;
          var origin = protocol + sr_origin;
          $.ajax({
                         type:"POST",
                         url :origin+"/appName/post_view",
                         data:{
                                     "DATA_X": x,
                                     "DATA_Y" : y,
                                      csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val() 
                                   },
            datatype:"json",
            error:function(data){ alert('Error:');},
            success:function(data){ alert("Success");}

          });
  • On the view side we need to provide a map for the URL : /appName/post_view mentioned above as : url (r'^post_view$',views.post_view,name='post_view') in the url.py file located within the appName folder [appName is the name of django app from which we want to make the call to view function]
Once this mapping is done we are good to make our ajax call ! 


Tuesday, December 9, 2014

Get Last N Recent Django Model Instances

Problem:
We have our good old Django employee application and we want to show 5 recent joiners in the team on a Django template.

Solution:

Lets take the case of Employee instance having a created_date as one of the attribute that will define the datetime when the employee entered the system. We will follow the following approach:

  1. Get the queryset of django instance sorted in decending by created_date attribute
  2. Pull out top 5 or n from this list
  3. Please note the method in the sis a static method as it is not dependent on the instance but the Class itself
Code Sample: