Improve your local Django local development with Nginx
Oct 20, 2010
Dick Brouwer
2 minute read

The Django development server is great for 2 reasons:

  • Instant refresh on code change
  • Easy debugging with (i)pdb and/or print statements

However, this comes at a cost. It’s relatively slow, and, more problematic, it’s single-threaded. Many argue the latter isn’t a biggie for local development (except when doing load testing or verifying multi-threaded behavior), but I don’t fully agree. I’ve had many occasions in which I had to load an image form the server while Django was still serving a request. For example, ListCharming uses the Pisa PDF converter to attach a PDF to an email. Testing a view that sends an email using Pisa fails, because Pisa tries to render an html for conversion while the Django dev server is still busy with the initial request.

An idea I had was to just replicate a production environment on my laptop using Nginx and Gunicorn. This works, but you lose the dev server advantages mentioned earlier. A better approach is to serve your static media with Nginx, and have the Django dev server handle the rest.

Setup on OS X (using Homebrew):

  1. brew install nginx
  2. Edit /usr/local/etc/nginx/nginx.conf and add the following config (for example in your server directive)
server {
  listen 80;
  server_name sitename.local;

  location / {                                                                                                                    
      proxy_pass  http://127.0.0.1:8000;
  }

  location  /media/ {
      root /var/django/websitename/;
      expires 24h;
  }
}

As an added advantage, your Django devserver output won’t get cluttered with static media http results.

Note: if you get “permission denied” errors, set the user directive at the top of nginx.conf like so: user root wheel (do not do this in production)



comments powered by Disqus