Some Django tips

I’ve been using Django for web development at work for a few months now, and here are some tricks I’ve picked up along the way.

  • Install IPython: IPython is an interactive Python shell, much like when you just type “python” at your prompt. The nice thing about IPython is that you can use it like a breakpoint in your code. You import IPython.Shell.IPShellEmbed and you call IPShellEmbed()() where you want execution to stop. When this point is reached in your code, you will find yourself in an IPython interactive session with all the variables of your code. You are then free to play around with the variables, modify them and do pretty much whatever you want. I cannot emphasize enough how useful this is.
  • ChoiceField vs ModelChoiceField: When you write a form with newforms, if you want a ChoiceField or MultipleChoiceField that has its choices from the database, use ModelChoiceField and ModelMultipleChoiceField instead. When you give the choice argument to ChoiceField, the data is loaded at import time. This has two consequences: (1) when you add new data, it won’t appear in your form until you restart the server, and (2) in your tests, your production data will be loaded into your form instead of your test data.
  • Add your custom form validations: The current documentation for newforms does not cover how to do custom form validation, but it’s hidden somewhere in the tests. It’s really simple to do, you write a clean_XXX(self) method where XXX is the field that you want to test. The method should raise django.newforms.ValidationError if the input is incorrect and return the data if it is. Here’s a simple example:
        def clean_number(self):
            if 1 < self.clean_data['number'] < 10:
                raise ValidationError(u'Please choose a number between 1 and 10')
            return self.clean_data['number']

    Note: I’m not quite sure, but I think the property name for the clean data has been changed from clean_data in 0.96 to cleaned_data in the development version.

  • Use the {% url %} tag: The {% url %} tag takes a view name and its parameters and does a reverse lookup to return the wanted URL. This means you can make modifications to your file and your links will keep on working. The documentation for this tag is here
  • Learn to write template tags and filters: There is a very strong chance that you will need to perform a computation in your template at some point. You should definitely learn to write tags and filters for that reason. Here’s an example, you have a generic view to display a list of objects and the list is paginated. You want to add links to every page number at the bottom of the list. You will need to loop from 1 to the template variable pages. A small filter such as {{ pages|range1 }} (range1 to show that it’s from 1 to pages inclusively) will help tremendously.
  • Generic views are really useful: Although I don’t use them all, the object_list generic view will surely become your best friend. It gives you free pagination! One less thing to worry about.
  • Make your own context processor: If you need to pass an information to every template, don’t do it by hand, create a context processor and add it to TEMPLATE_CONTEXT_PROCESSORS in your file. From then on, all templates that use the RequestContext class will have that information available.
  • Write tests: Not really a Django-specific item, but it’s always a good idea to have a complete test suite. Learn how to use django.test.TestCase with fixtures. Also learn how to use django.test.client.Client to be able to test your views.
About these ads

2 thoughts on “Some Django tips

Comments are closed.