Rajani's weblog

 
« Back to blog

My Favorite Django Tips & Features

1. Dont hardcode MEDIA_ROOT and TEMPLATE_DIRS use os.path.realpath(os.path.dirname)__file__)) 

hardcoding will cause problem while moving from dev->test->live

2. Dont hardcode static files in templates. use MEDIA_URL

EG: 

<script type="text/javascript" src="{{ MEDIA_URL }}js/jquery.js"></script>

In future if you change your cdn, you will have to change it only in the settings

To get the context variable use django context processor. Its very easy to write and this makes MEDIA_URL and any other variable you like available across all the templates 

        http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors

3. Use the url function to define the urls. Dont hardcode urls. Use reverse() in views.py and {% url %} tag in templates

4. Thirdparty app django-command-extension

This app is very useful. It gives some other useful commands  like

        shell_plus -  extension of shell. It will autoload all enabled django  models.

sqldiff - gives you the sql diff between the code and the DB

        show_urls - displays the url routes that are defined in the project

        graph_models - creates a GraphViz dot file 

        clean_pyc - removes all the pyc files

        reset_db - Resets a database

5. use pdb to debug django projects

6. dont copy paste html across templates. use {% extends %}, {% include %} and other builtin templatetags. write your own custom templatetags if necessary (they are very easy to write)

        http://docs.djangoproject.com/en/dev/ref/templates/builtins/

7. understand django middleware. Use this if you want to do some something before the request is processed / after the response is generated etc. - again they are very easy to write

http://docs.djangoproject.com/en/1.1/topics/http/middleware/

8. use django forms - they are really really powerful 

9. use django test client for unit testing. It acts a dummy web browser. Its very useful to simulate GET and POST request

        http://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client

 

Comments (1)

Aug 17, 2010
Rajani Karuturi liked this post.

Leave a comment...