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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

  • 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.


Source link