10 Insanely Useful Django Tips

There are quite a few great little tricks and tips one could use on their Django projects that would speed up development and save many headaches in the long run. From basic to obscure, these tips can help any skill-level of programmer become more adept with Django and all it’s glory.

Django is an excellent framework for Python. While it may not get as much ink as other popular frameworks like Rails, it is just as much a polished framework as any of the rest. It puts plenty of emphasis on the DRY principle (Don’t Repeat Yourself) in clean coding by automating many of the processes in programming.

1. Use relative paths in the configuration

For some reason, projects tend to be moved around in location from time to time. This can be an absolute bear to deal with if you don’t first plan ahead for the possibility. Rob Hudson has an excellent technique to ensure that your Django deployments can be moved around with ease, only having to edit a few lines of code in your settings files.

My default Django settings file has changed over time to now include settings that do not depend on the location of the project on the file system. This is great in a team environment where more than one person is working on the same project, or when deploying your project to a web server that likely has different paths to the project root directory.

Rob’s post has excellent code examples for setting up your Django installation in a very flexible way.


Photo by kaet44.

2. Use the {% url %} tag

Instead of hardcoding individual links, try using the backwards compatible {% url %} tag to achieve the same result. This will give you the absolute URL, so that if, heaven forbid, your Django project moves the links will still remain in tact.

Essentially the {% url %} takes a view name and its parameters and does a reverse lookup to return the queried URL. If you make changes to your urls.py file, the links won’t break.

While it’s not the most advanced tip, it’s an excellent technique to use in your django projects.


Photo by Dave_Apple.

3. Use Django admin for your PHP apps

Possibly one of the greatest features of Django is the user authentication system that Django has built straight into the core. It’s seriously easy to set up, and it comes packed with a robust system to authenticate users and configure other necessary settings.

This user system is so awesome that it’s even been suggested to use Django as your admin area for your PHP application. Here’s Jeff Croft on why Django is a great solution for an admin system for any application, regardless of language:

One of the core philosophies of Django is loose coupling. Besides the more alluring free-love connotation, this mean that each of the layers of Django‚Äôs ‚Äústack‚Äù ought to be independent of the others, such that you can choose to use only bits and pieces of it, and/or slide in other components if you prefer. Lucky you, it‚Äôs incredibly simple to learn the basics of Django‚Äôs model layer, which handles database schema and object-relational mapping ‚Äî even if you don‚Äôt know Python. Anyone can create a database schema in Django and get the crown jewel of the framework — it’s admin interface — with very little work, even if you plan to write the application logic itself in another language.


Photo by Cloudzilla.

4. Use a separate media server

Django allows you to serve static files in your development environment, but not your production environment. Why? It’s not efficient. At all. Jacobian.org gives an explanation.

Django deliberately doesn’t serve media for you, and it’s designed that way to save you from yourself. If you try to serve media from the same Apache instance that’s serving Django, you’re going to absolutely kill performance. Apache reuses processes between each request, so once a process caches all the code and libraries for Django, those stick around in memory. If you aren’t using that process to service a Django request, all the memory overhead is wasted.

By using a separate server to house and serve these static files, your performance won’t suffer. If you didn’t want to buy a server you could use Amazon S3 to house the files relatively cheaply.


Photo by winkyintheUK.

5. Use the Debugger Toolbar

Debugging tools for any language are invaluable. They speed up development by spotting errors in your code and potential pitfalls that might happen. Rob Hudson has recently released the django debug toolbar to help with debugging code, and it could greatly help any developer.

The toolbar itself is a piece of middleware that instantiates each panel object on request, and performs processing and rendering as the response is being written back to the browser. In this way it is essentially a set of middleware classes (the panels) grouped together to display a single toolbar. Each panel subclasses a base panel class and overrides a few methods to render the toolbar.


Photo by winkyintheUK.

6. Use Django Unit Testing

Unit testing is a great way to ensure that your changes to the code that it works as expected and doesn’t break any older code to maintain backwards compatibility. A great feature in Django is that it’s incredibly easy to write unit tests. Django offers the ability to use the doctest or unittest straight out of the box.

Django’s documentation offers a great tutorial and some sample code on how to set up unit tests to keep your code running smoothly and spot any nasty bugs.


Photo by dave_apple.

7. Use a Cheatsheet

Is cheating wrong? I hope not. This nifty 2-page cheatsheet contains some golden nuggets within arm’s reach that one might have to dig around the Django documentation to find.

The cheatsheet features these helpful topics:

Templates

  • Template tags and their options
  • Template filters and their options
  • Date formatting syntax quick reference

Models

  • Fields and their options
  • Common field options
  • Meta class options
  • ModelAdmin options

Forms

  • Fields and their options
  • Common field options
  • Standard error_messages keys

We all know time spent looking at documentation is time spent not solving the world’s problems through code. And no good programmer wants that.


Photo by quimpg.

8. Utilize django-chunks

Django-chunks is essentially a way to create blocks of reused code in your templates. Except creating the blocks is made even easier by using Django’s rich text editor.

Well it essentially allows someone to define “chunks” (I had wanted to call it blocks, but that would be very confusing for obvious reasons) of content in your template that can be directly edited from the awesome Django admin interface. Throwing a rich text editor control on top of it make it even easier.

By replicating bits of reusable code, django-chunks ensures that pieces of the layout can quickly and easily be changed if need be. While django-chunks is really only a model and template tag, it can greatly speed up development by replicating processes.


Photo by Vince Huang.

9. Utilize Memcache

If performance is going to be an issue with your Django-powered application, you’ll want to install some sort of caching. While Django offers many options for caching, the best by far is memcached. Installing and using memcached is fairly easy with Django if you use the cmemcache module. Once the module is installed, you just change a single configuration option, and your Django pages will be served lighting fast.


Photo by lastrandy.

10. Stop hacking scripts together and just use Django

If you still don’t fully understand Django’s power after reading this article, there’s a logical reasoning for using Django in your next project: You save time hacking together designs with different sets of software. Jeff Croft explains why creating a project in Django is much more efficient than trying to hack together scripts.

Now, if you’re used to building sites using a blogging app (WordPress, TXP, etc.) as a CMS, you’re used to getting all that for free. But you’re also getting a lot of things built-in that maybe you don’t want (unless, of course, you’re building a blog). The limitation I ran across in using a blogging app for my personal site is that I wanted it to be more than just a blog. As soon as I tried to hack a blog into a photo gallery, or a links feed, or a statistics database, a game of Sudoku, or whatever else I could think of, things started to get crufty. I also built a website in which I tried to use a discussion forums app (vBulletin) as a CMS, and that had the same results. It worked — sort of — but it wasn’t extensible, was very hackish, and just generally was inelegant.

With Django, you get all of these things and none of the limitations of a blogging app.

Django allows you to expand your website into literally any direction without having to worry about hacking the design or making sure the scripts and databases are compatible. It just works.


Photo by JennyHuang.
  • Subscribe to the NETTUTS RSS Feed for more daily web development tutorials and articles.

Glen Stansberry is a web developer and blogger who’s struggled more times than he’d wish to admit with CSS. You can read more tips on web development at his blog Web Jackalope.

If you found this post useful, please say thank you with a Digg or Stumble.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.image2markup.com Ivan

    Hmm, I should give D a try :)

  • http://www.freshivore.net Vince

    Well it’s good in practice to learn a new language every year so, here I come python!

  • http://hybridlogic.co.uk Luke L

    I used Django for a dev site and absolutely loved it, by far my favourite framework. However it just wasn’t production viable on my Dreamhost server so I’ve gone back to PHP. Django and Python in general are beautiful products, but it wasn’t worth me moving server to gain that power.

    • Teo

      You’re crazy man. Yes it DOES worth moving! Wake up!!! php is a dinosaur.

  • http://www.satedproductions.com Michael Thompson

    @Luke L: It’s possible on Dreamhost: http://wiki.dreamhost.com/index.php/Django

    Django is hands-down the best framework I’ve ever used, and I haven’t heard a bad thing about it from those that have spent time getting used to it and releasing a few small “hello world”-like apps.

    Those unfamiliar are either scared to try Python, lazy, wishing for something like CPAN* or just plain dumb. That’s right: dumb. It’s shocking to me how many jumped onto the RoR wagon but are fearful of Django.

    It will make your life easier, it will save you time, it can always be modified to suit your needs and you will love it once to dive-in.

    * Comparable sites: http://pypi.python.org/pypi and http://www.djangosnippets.org/

  • alex

    Great Post

  • Marcus

    Nice to see some Django related articles here on Nettuts! Thanks for sharing these great tips!

  • wang

    I’d like to read some article about Django tips,
    thanks for this awesome post.

  • http://www.insicdesigns.info insic

    ive heard this Django thing before, maybe i give it a try now.

  • http://www.instantshift.com Roshan

    Nice post. Thank you. I will see if I can try this out. :)

  • http://www.freshclickmedia.com Shane

    I’ve been hearing quite a bit about Django of late – and I know that Python is used quite extensively by some big players like Google.

    Hmm… Dreamhost problems seem quite familiar (RoR anyone)… I’d rather not have to jump through hoops to get things up and running.

    However, as good as these tips are, perhaps an introduction to Django is called for on nettuts? What do other readers think?

  • http://stefanimhoff.de/ Stefan

    There is a good screencasting series on “This Week in Django” (http://thisweekindjango.com/screencasts/).

  • http://devjargon.com Alex

    I’m pretty stoked about the Django tuts. I hope that we’ll see more. I’ve been doing alot of research on it, and it seems like a very nice tool.

  • http://www.ben-griffiths.com Ben Griffiths

    Some interesting tips, thanks :)

  • Greg House

    Is your article about programming or icy stuff? You really confused me there.

  • Chekke

    Awesome post, thanks for the tips.

  • http://brice.sharenow.com Brice

    Why there is nothing about debug ?

    Howto debug… really easy ! put those lines where you want to get a break :
    import pdb; pdb.set_trace()

    run the server with python
    manage.py runserver -p 8888

    you now just have to go to the page with your web browser (enter the address of the host or localhost if the server is running on same computer of your web browser) and add the port (ie. http://localhost:8888 ). Your done, once you go to the page where the set_trace() method is read, the server will break at this position and the terminal where you run the server will show you the prompt, allowing you to go trough your code and variable :)

  • http://rob.cogit8.org Rob Hudson

    There are a lot of people commenting they should try Django. Right now, to celebrate the release of Django 1.0, Webfaction is offering a special promotion on their hosting. (I think it translates to 1 free year of a Shared 1 plan.)

    See their blog post:
    http://blog.webfaction.com/django-1-0-is-here

    Sign up (with my affiliate link):
    http://www.webfaction.com?affiliate=robhudson

    Cheers!

  • Christian

    Why on earth would you put all those pictures there? It looks awful, don’t get me wrong – the pictures are great. But combined with a Django post they put me way off.

  • http://jeethurao.com/blog/ Jeethu Rao

    No mention of using Werkzeug to debug Django apps ?
    Thats probably the single most awesome debugging tool available to a django developer.

  • Blu3ness

    Can we not have pointless photograph in a discussion about Django? That just seems totally random and irrelevant. Plus, you can save a few bucks on less network traffic :P

  • Pete

    Tip #11 : Use WebFaction ( http://www.webfaction.com ) for hosting. You’ll be glad you did :)

  • http://Widgy.net Diego Gomes

    Awesome tutorial.

    You’re in the right way to become the greatest site for tutorials in webdesign and dev.

    A cool thing would be following the hype and publish a introducing Google Appengine development!

  • http://www.innovationsopen.com mzee@richo

    Nice stuff .
    Google App Engine stuff next please

  • http://www.webspot0007.0fees.net Jammer

    Thanks for this nice tutorial, lol!!

  • http://www.instantshift.com Roshan

    Lots of ice burgs. lol. nice tips.
    keep them coming. Thank you.

    Roshan
    Freelance Developer
    http://www.instantshift.com

  • Pingback: 20 Excellent AJAX Effects You Should Know - NETTUTS

  • Pingback: How Web Development Created Blog Action Day

  • Pingback: » links for 2008-10-02 | Paul Cowles

  • chris

    Nice post, but I have to question Tip 3: Why use Django’s nice user authentication module for PHP apps, when you could just use Zend Framework’s equally nice user authentication module, plus all the other PHP goodness contained in ZF? PHP5+ZF is a pretty powerful combo, if you want to use PHP. But if you want to use Python, then I like the look of Django, so thanks for the tips!

  • Pingback: Ed The Dev » Insanely useful Django tips

  • Pingback: 酷壳 » 你应该知道的20个Ajax技术(11-20)

  • Pingback: Pinderkent: Some Django tips and tricks pages that I've found helpful.

  • reign

    what a photo shot beautiful view an ice berg….hope i can go there to see in person what feeling if you see a view like that what kind of excitement…

  • Pingback: Django: Einführung in das Web Framework | Frameworks, Open-Source, Server | Dr. Web Magazin

  • http://devcheatsheet.com/ Tim

    More Django cheatsheets here: http://devcheatsheet.com/tag/django/

  • Pingback: Django Öğrenebileceğiniz 24 Kaynak | ftoptas blog

  • http://www.armeki.com Armeki

    Good tutorial but i liked photos more :)

  • http://www.cuthemustard.com Marconius

    Amen, brother!

  • Pingback: My Stream » Python from Scratch – Create a Dynamic Website

  • Pingback: Python from Scratch – Create a Dynamic Website « CSS Tips

  • Pingback: NashItUp

  • Pingback: 10个实用的Django建议 - 博客 - 伯乐在线

  • Pingback: Faruk Toptaş » Django Öğrenebileceğiniz 24 Kaynak

  • Pingback: django | Pearltrees

  • Pingback: A Nice Dose of Python Tutorials For Professionals | codeManiac - Snippets, Templates, API and the best developer content

  • praba

    Great post.. thanks buddy