Usefull tips to start a new project with Django
By AkH, 9 months ago, modified Feb. 19, 2008
This is not another how to install Django, but some good to be known tips for starting a Django project the right way.
Requirements
- Use Python >= 2.5 (sqlite and others usefull libs are included), on Mac prefer the Macports python, cause addon's installations will be simpler and your system will remains clean (installation in /opt/local)
- Install ipython It will provide you a better manage.py shell
- Install docutils, it will generate you a usefull documentation, that you can browse via the
Documentation
link in the Django admin view - Django sources: Follow django trunk for a maximum of time, the API is becoming fairly stable, no need to work on a fixed version at the early parts of your project
Charset
- Since > 0.96 Django support unicode everywhere use it: Start all your py files with
# -*- coding: utf-8 -*-, utf-8 is the solution to most charsets problems, abuse it (All my visitors are using ASCII, is not an excuse, except if you live in 1980) - Only define
_unicode_model methods and let Django deal with_str_alone See __unicode__ doc - Think in unicode: A string is no more a
"my text"butu"my text",_unicode_method needsreturn u"Something"
Models
- Only use null=True for non-string fields such as integers, booleans and dates: Avoid using null on string-based fields such as CharField and TextField unless you have an excellent reason. See null model doc
- Use fixtures to reimport data and test your apps
manage.py dumpdata --indent=4 > initial.jsonandmanage.py loaddata initial, don't spend time to reinsert data everyday with the admin - Spend a lot of time on your model, it describes your data, enforce every field, for example use
null=Trueonly where needed - Handle static choices the right way, use IntergerField for choices list
- Storing additional information about users: At this time the solution in not to subclass User but to set
AUTH_PROFILE_MODULEin your settings and let play withget_profile()See addional informations about user - Use the admin to test your model, what could be better than a web browsing to validate your model ?
Views
- Create a urls.py per application and call it from the root urls.py:
(r'^myapp/', include('myproject.myapp.urls')) - use @transaction.commit_on_success decorators when you are inserting data, the action to commit modifications in db can be associated to the return code of your view (200 ok django will commit), It makes your inserted data more consistent, See my earlier post for a little case study
Debug
- Put a
assert Falsein your code (in view) it will act as a breakpoint, you can now browse the local vars in the debug page - Use template language and {% if debug %} to put some sql queries debug facilties in your views (change INTERNAL_IPS in your settings.py if you are using a remote server)
If you don't have a template at the moment you need to debug your sql, use this anywhere in your code and browse the debug page
from django.db import connection
a = connection.queries
assert False
- At some points profile your code before production
- use Django to serve your static files, it's simple to configure, but should only be used in devel/debug situation
manage.py shellwill become your best friend to debug, here is a way to autoloading the models from the shell which is a boring operation if you have to type it 50 times per day
Production
- Create a settings-dev.py and a settings-production.py then link settings.py to the one you need
- Regularly test your code against the targeted production platform: Sqlite is not Mysql nor Postgres, Apache, mod_python, mod_wsgi are not the embedded server, they comes at a price: some side effects
- mod_wsgi does not allow printing on stdout:
sys.stdout access restricted by mod_wsgiit will raise an error, don't forget to remove them before production
I hope we will update this list with new tips.
UPDATE: 08/02/20 Fix Malcolm recommandations, add Storing additional information about users
UPDATE: 08/06/20 add assert False tip


Comments
Nice tips; well presented. Two small corrections, one big and one small.
The big one is about LANGUAGE_CODE: that is the default locale used to display messages in. "utf-8" is not a locale. You will set LANGUAGE_CODE to something like "en" or "de", etc. Since Django doesn't ship with "en-au" or "en-us" variants, leaving LANGUAGE_CODE alone will give you default English messages (as if it were set to "en"), which isn't a terrible default.
Secondly, regarding null=True on CharFields. This isn't a preference that the user has control over. Django will not insert NULLs into CharFields. Ever. This is a convention because of the impossibility of telling the difference between "unset" and "intentionally left empty" when data is submitted via a form (HTML doesn't have a concept like SQL's NULL). So we always treat that as "intentionally left empty", i.e. "", not NULL. So writing null=True on a CharField is just a waste of typing; it won't ever have an effect.
Hi Malcolm
You're right about LANGUAGE_CODE, I made a mistake with DEFAULT_CHARSET, which is something we don't need here, fixed.
For null=True on CharField I'm glad you've posted this details, it makes senses, but the Django doc is a bit confusing about it, and says Oracle backend is a special case.
Thanks for your comments.
see- http://blog.doughellmann.com/2007/1...
whoops, missed off the main part of my post:
for mac i would personally recommend using the standard leopard python install and then using virtualenv to create an separate environment where you can install any packages cleanly and into a directory of your choice. will keep your system far more clean than installing the macports python version.
that's how i do it after causing all sorts of mess in tiger by opting for the macports python installs
un petit messagev pour te dire que ton blog est rrès plaisant :)
very good.