Friday 4 May 2012

Changing the default domain name from example.com in Django

By default when Django is setting up the database it installs an instance of the Site model and it sets it’s domain name to example.com. This isn’t much of a problem in development or live environments because it can be changed in the admin or with initial_data fixtures. When testing, however, it is a problem and it’s a problem that could be easily fixed by introducing a setting that allows users to set the domain name of the default site.

Context

I’m authoring an ecommerce checkout application for Django that will soon be open sourced. It comes bundled with a few payment methods that I’m forced to integrate with Paypal & Sagepay a lot because stripe is not yet available in the uk. When testing the application the Site.objects.get_current() method returns example.com and this is causing the test to fail because there is no API endpoint configured at example.com. The first answer that popped into my head was be to set the domain on the site using the setUp() method of the test case. But then I thought what would I set it to? It’s impractical to try and guess the domain name that the end user would be using. Having a setting available in this use case would be very beneficial, but officially this isn’t supported.

My Solution

I added a setting to settings.py and in the tests I’m checking for example.com and if it’s detected, just bailing the test. That way I know that I can test it here and should the end user want to, then I’ll make this explicitly clear in the docs.

 DEFAULT_DOMAIN = 'dev.mrsmoo.eu'