10 Django Trouble Spots for Beginners

10 Django Trouble Spots for Beginners

Tutorial Details
  • Technology: Django
  • Difficulty: Beginner

Django is an incredibly-powerful web framework, but using it can be a bit daunting for new users. I found this out the hard way over a year ago, spending hours struggling with even the most basic of concepts. If you're new to Django, (or MVC frameworks in general), you're probably going to have to shift your thinking a bit to use this robust framework. Here are some of the issues that I had to struggle with before I fully understood them. Hopefully, this will save you hours of struggling.


1. It's Not a CMS

Django isn't a CMS. It can't do everything that WordPress or Drupal can do right out of the box. That said, you can do infinitely more with Django, because it isn't a CMS.

If you have a background with, for example, a platform like WordPress, it's going to take a while to wrap your head around the fact that you're going to have to do a lot more things manually, such as creating urls or modifying settings. Most of the configurations won't be done in a UI, but instead with Python files.

While Django does come with a pretty nifty admin area straight out of the box, configuring Django sometimes isn't as easy as a standard CMS.


2. Local Environment Setup

One of the biggest initial hurdles that new users face is configuring their local environment for Django. For many beginners, it takes longer to install the framework locally than to build their first app. PHP frameworks like CakePHP are pretty much ready to start using once you've downloaded them on your local machine.

Installing Django and configuring it to run on the local machine can be kind of tricky, especially if you're not familiar with concepts like symlinks. The Django install docs are pretty comprehensive, but if those don't work for you search for some video instruction or platform-specific documentation.


3. Projects vs. Apps

If you're new to Django (or MVC frameworks in general), odds are the terms "projects" and "apps" might be a little confusing.

With Django, a Project is just a collection of apps. Say you were building a YouTube clone; you would create a project, "MyTube", that would contain apps like "videos", "comments", "ratings", "blog", etc.

Apps are similar to modules in a CMS, except you build them from scratch. They're a lot smaller in scope, typically performing only one main function. For the MyTube example, you wouldn't just create one app that allowed users to upload videos, comment on them, rate them, and anything else. You want your apps to be small in scope, performing only one or two functions by themselves.


4. Template Inheritance

Template inheritance is one of the best features of Django, but it usually takes a while to truly understand.

With a traditional CMS, you might split reusable parts of a template out into their own files (like a header file), and include them in each of the templates. With Django, you create a base.html template, and you specify blocks that can be overwritten in child templates. This keeps your code more reusable.

So, for an example, you might have a base.html template that has this:

<div>
  {% block content %}
    <p>Here is our content that will be overwritten</p>
  {% endblock %}
  <p>Other stuff that won't be overwritten.</p>
</div>

Then in another template you may choose to overwrite the {% content %} block. Instead of having to include a sidebar file into the design, we just simply do something like this:

{% extends base.html %}

{% block content %}
I'd like a different content block!
{% endblock %}

This extends the base.html. This method allows you finer control over your templates, and ensures that you're not creating duplicate code.

To learn more about the power of template inheritance, check out this article on the power of Django template inheritance.


5. Separation of Code and Media Files

Because Django doesn't serve media files itself, it likes to separate the media files (images, JavaScripts, stylesheets, etc. ) into a directory away from the apps. This allows you to decide how you're going to serve those static files. You could use a separate webserver or cloud services like Amazon S3 to serve the files.

Your project files might look something like this:

MyProject
  - app
  - app2
  - media
    - javascript
    - stylesheets
    - images
  ....

6. Migrations

Database migrations are a trouble-spot for many beginners. This happens when you already have fields in your database (production or development), and you add something that modifies the database.

Other frameworks like Rails have database migrations built in. With Django, however, unless you use a third-party solution, you have to do the migrations by hand. Fortunately, there is an excellent third-party tool that handles Django migrations: South.

South allows you to perform database migrations, much like Rails allows, and is easy to roll into your existing project. It's powerful and simple, and takes care of the issue of database migrations that Django has. Here's a tutorial that has examples of how South works.


7. Local vs. Production Environments

Django comes with sqlite, a simple flat-file database that doesn't need any configuration. This makes prototyping fast and easy right out of the box.

However, once you've moved your project into a production environment, odds are you'll have to use a more robust database like Postgresql or MySQL. This means that you're going to have two separate environments: production and development.

Django doesn't really have logic baked in that allows you to easily switch between two different settings without manually editing the settings.py file. For example, having the setting

DEBUG = True

is helpful for local environments, because it provides helpful error messages when code goes bad. But if you're on a production environment, you'll never want users to see your error messages, so you'd need to specify –

DEBUG = False

.

There is a way to automatically toggle between the two environments, using this quick modification:

  import socket

  if socket.gethostname() == '<a href="http://productionserver.com" target="_blank">productionserver.com</a>':
      DEBUG = False
  else:
      DEBUG = True

You can reuse the socket bit in different areas of your settings.py as well.


8. Writing Custom Template Tags

Template tags are an insanely useful aspect of Django. In fact, it ships with many built-in template tags right out of the box.

However, if you're wanting to write your own custom template tags, it can get a bit tricky. Here's a simple example of writing a custom template tag that should give you a better understanding of how template tags work and how to create your own.


9. Django User Authentication

Django comes with a great user authentication system in the project admin that you can use to manage users. However, the user authentication system doesn't provide a simple way to allow non-admins to create user accounts. CMSs, like Drupal, handle this beautifully right out of the box.

There are a few great options for public user authentication systems that provide this missing functionality. The most popular third-party solution is probably django-registration. It's simple yet flexible, and provides everything you need to get user signups in your application.


10. Generic Views

Generic views are incredibly powerful, and can save you a lot of time writing views for your Django app. However, most beginners don't know how useful and powerful they are.

For example, if you want to create a flat page for your homepage, but want to style it differently, you can create a template in your flatpages template directory that utilizes the direct_to_template view.

Aside from creating the proper template, you'll need to modify your urls.py file to point to it:

urlpatterns = patterns('',
  (r'^$', 'django.views.generic.simple.<WBR>direct_to_template', {'template': 'homepage.html'}),
.....

Now, we have a homepage with a custom design that doesn’t require writing any custom views. I’ve utilized this technique many times instead of writing extra views.


Conclusion

Once you've worked through all the tricky areas that catch most beginners, Django will prove to be a really fast and powerful tool for building web applications. Don't get discouraged if you find yourself confused early on. You can always find help within the Django IRC channel; Stackoverflow is another excellent place to ask questions.

Tags: django
Add Comment

Discussion 34 Comments

  1. Davidmoreen says:

    The thing that discouraged me from django was when I first installed it on my local machine and made an app, there was problems with the database model thing. Which of course I didn’t have time to fix it, so I just set it aside.

  2. lawrence77 says:

    Bookmarked for future use when i dive into Django :D

    welcome back Glen after some months :)

  3. Dale Hurley says:

    Would love to know how Django compares to CodeIgniter?

    • Compares how? I mean, Codeigniter is a PHP Web framework that runs through an apache mod (not always apache mod but typically.) Django is a Python Web framework that runs via apacha mod (or cgi, etc.) PHP is typically considered a “lower level” language (it came out of a template language specifically for web development after all.) Python was designed to be a more generic scripting language (probably much more powerful than PHP. Certainly more OOP.) There are many elements of Python I like better (but some I hate.)

      I think you need to be more specific here.

      Cheers.

    • Well, first of all Django uses Python, which I personally prefer. Other than that I would say that Django takes a bit longer to learn but has a more object-oriented approach to database operations (= no SQL).

      • Kyle Hayes says:

        No SQL is not always a better approach. Can leave a lot to be desired when the time comes down the line to make database operations more efficient.

      • @Jonas Its called an ORM http://en.wikipedia.org/wiki/Object-relational_mapping and you are not forced to use it.

        @Kyle You can always make raw sql queries (or non sql queries if you are using a NoSQL DB)

        @Brett The webserver that takes the HTTP requests has nothing to do with the language or the framework. Nginx (http://nginx.org/) seems to be popular these days and mod_python (http://attic.apache.org/projects/quetzalcoatl.html) is dead now most people use wsgi (http://wsgi.org/wsgi/). Also PHP is not a lower level language than Python, they are both scripting languages. Python is much more versatile language.

        @Dale I have done very little with CodeIgniter but the biggest difference (other than being a completely differnet language) there is (was) no ORM for CodeIgniter when I looked so people have hacked PHP Doctrine or some other ORM into it.

        The ORM for Django is not perfect but it is much easier to use than other ORMs like Ruby on Rails Active Record.

        For anyone looking to learn Django (and Python) this is a great start http://lightbird.net/dbe/index.html

  4. w1sh says:

    MORE PYTHON/DJANGO TUTS! FOR GOD’S SAKE MOARRR!!!!

  5. Python is a very powerful language that I would like to learn how to use better and more efficiently.

  6. Leandro says:

    Django rocks :)

  7. piyanistll says:

    very nice working thanks a lot

  8. jem says:

    Django is my most favorite framework by far. And Python has got to be one of the more fun languages to code in, it feels very natural.

    I’d love to see more quality Django screencasts on nettuts.

    There’s also some other awesome Python servers/tools like Tornado that probably blow most anything away in the speed department.

  9. netoxico says:

    very good I would love to see more django and python on nettus, and now that the new django 1.2 is out

  10. Felix says:

    I really want to dive into Django , can anyone recommend a good Django book?

  11. Obviously there are greater concerns than performance at this level, but I am curious to know if there are any performance hits for using template inheritance. It seems like this could be a trouble spot.

    But the concept is very interesting. Nice writeup.

    • Eric says:

      Using Template Inheritance doesn’t slow performance. Unlike many php frameworks, django does a single compilation step with the server is started and is running on bytecode for the life of the application, where as php by default is compiled and every request.

      With django templates, django only has to parse the bits it recognizes and template tags or filters. If you pass it a straigh HTML page with no tags, it doesn’t parse anything, it does 1 scan and returns the page un touched.

      With most django applications, your speed limitations are I/O and ram bound. Disk reads and database calls are where you will lose performance. Django’s ORM allows you to be very expressive on getting data from the database and beginners will get carried away doing too much at once leading to hundred of database calls and JOINS.

      I have built complex pages that have 9 – 10 different templates and dozens of template tags and filters, and it’s page load time is still under 1/2 second. I would say in the grand scheme of django rendering templates is probably the 1 step you don’t need to worry about.

  12. florian says:

    From a designer (non programmer) perspective. What is django?? What can you use it for? Not sure I understand the concept

    • It is essentially an application programming framework (similar to Ruby on Rails), but written in the Python Language.

      It helps you do (well) the things that sites do over and over again.

  13. Looks like Python has got to be one of the more fun languages to code in.
    If there are any performance hits for using template inheritance?

    Thanks for sharing.

    • DED says:

      In answer to the question of performance and the Django’s template inheritance. No, there is not a performance hit. Really there is no reason why there would be. Django was built to run on template inheritance, in fact it always uses this and is quite fast. I think the confusion comes from how this idea plays out in frameworks like Smarty in PHP. But in Django the idea is somewhat different. Templates are treated as strings that contain placeholders, and there is only a little programming (looping and conditionals) allowed in a template. Generally they are files on the server, and the place holders are like variables. The idea is to separate the programming logic from the display markup. This way designers and developers don’t step on each other’s toes. It works very well.

  14. mohit says:

    I am firlst time visting this site and I think its nice.
    Great tutorial…nice work!
    visit : movies.ewebtutorial.com

  15. Antony says:

    All of the sites I’ve designed over the past couple of years or so have been built on a bespoke CMS using Django as its foundation. The developer I work with convinced me to go with it and we’ve not looked back since. Developments are rapid, the CMS is fast, the standard UI is pretty intuitive too.

    It seems incredibly flexible, doesn’t demand huge amounts of power to run (approx 20mb application memory for a small-medium sized development).

    You will of course require hosting that is up the job, there are a number of host out there but I use http://www.webfaction.com/services/hosting we switched from a larger and cheaper host just over a year ago which cause a couple of sites to crash from time to time, we couldn’t get to the root of the problem so switched to a host specialising in Django and have enjoy slick and fast sites ever since.

  16. Oziel says:

    How about django x rails x grails comparison? Seems to me that grails, because of java, is the easiest to learn, but also because of java, grails its the more memory hog of them all.

  17. bmw ops says:

    A wonderful article. In my life, I have never seen a man be so selfless in helping others around him to get along and get working.

  18. fuSi0N says:

    Since I use Django framework for my thesis I find this article extremely encouraging.
    Keep up the good work, more django tuts please! :)

  19. sinosells says:

    Automotive Diagnostic Tools & Equipment

    sinosells, the best place for online shopping from China

    sinosells selling big brands of auto parts: auto auto diagnostic tool, ECU Tools, Locksmith Tools, Auto Accessories, Digital Products, odometer correction, diagnostic scanner, auto scanner, immo code reader, airbag reset, transponder key, key blank.
    Come in need of assistance Website: http://www.sinosells.com
    sionsells “faith-based, customer first, service first”, sinosells price will be more robust steps, boarded the update stage.

  20. Wassim Halawani says:

    That was very encouraging.

    @Justin Hamade The link you shared is all i needed to get going. Thanks a mill.

  21. gamebit07 says:

    Fr database migration in django, a great tool is available here http://south.aeracode.org/ its like a version control system to your database, its really handy when it comes to database migration.

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.