2008-04-08

Tips #2

What time is it now? It's time to give you some more tips about Django development!

Use batch scripts to automate manual routines. Do not repeat yourself extracting and compiling translatable strings, starting and stopping development web-servers, updating and committing your project to the version-control system in the console. Write batch scripts which you can run within one mouse click instead.

Define overwritable constants in your applications. Your applications are likely using some values that might be defined as constant values, i.e. the dimensions for avatars of users. Define those constants so, that you could overwrite them in the project settings if necessary.
from django.conf import settings
SOME_SETTING = getattr(settings, "SOME_SETTING", "default value")


Have one view for site-related JavaScript globals. Django views usually return (X)HTML-based responses, but it can return XML, JavaScript or others as well. Usually you will hold all you JavaScript functions in static files, but there might be some situation, where you need to get information related to database or project settings, for example, the MEDIA_URL.
The following view might be used to display a javascript page directly from a template. Just pass the template to the view in your urls.py file.
from datetime import datetime, timedelta
from django.views.generic.simple import direct_to_template
def direct_to_js_template(request, *args, **kwargs):
response = direct_to_template(request, *args, **kwargs)
response['Content-Type'] = "application/x-javascript"
now = datetime.utcnow()
response['Last-Modified'] = now.strftime('%a, %d %b %Y %H:%M:%S GMT')
expires = now + timedelta(0, 2678400)
response['Expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S GMT')
return response


And now it's time to go home and to get relaxed.