We have been creating some real cool stuff with drupal CMS and django since January 2007. That is why most of our clients come back to us when they have to get a second(or third or forth) project done
Drop us an email at info (at) ikraftsoft (dot) com to know more about what kind of work we have accomplished and what our clients say about our work.
Visit http://ikraftsoft.com if you prefer, but most of the stuff about our knowledge is here ;).
A common task in a web developer’s day to day work is to add an ‘active’ class to anchor tags for styling the link to currently active page. In PHP world, this generally involves anĀ if-else chain. But how do we do it in Django?
I searched the web but couldn’t find anything specific; therefore I coded a simple template tags for the purpose.
This little template tag can be used both with url names as well as the actual url strings. Check them out.
Here is the template tag code.
and here is how to use it in your templates.
Recently I faced a problem in one of our Django project where I had to display drop down select box and checkboxes on a webpage which on initial page load had a about 20 - 30 choices. These choices could change via Ajax depending on the actions performed by the user. Also the choices come from a pool of hundreds of thousands of possible values.
Default forms.ChoiceField provided by Django, requires a list(or a tuple) of pairs of possible choices to be provided in the choices argument as follows.
The value of choices argument is used to build the html widget as well as for validating the form field. Therefore, if the submitted value for the my_choice_field is not present in the list_of_choices, an error is flagged and the form submission is not valid. Now we could not pre create a list with hundreds of thousands of possible values because of the obvious memory usage concerns and also the fact that we would have to modify the rendering logic of the widget to a very large extent which would have been time consuming both in terms of development & debugging.
For our particular use case, we solved this issue by subclassing forms.ChoiceField and overriding its valid_value method as described in following code snippet.
The valid_value method is fired to validate the value of the ChoiceField received through the form submission. The default definition of this method simply checks the presence of the received value in the choices list provided during the definitions of form class. By overriding this method and adding our own logic to check for the validity of received value we solved this issue with simplicity and minimal time investment.
PS: We could not use the django validators system for this purpose because in the case of ChoiceField, validators are fired after valid_value method.