|Version 1 (modified by Lllama, 10 years ago) (diff)|
Four Days on Django
The aim of this page is to provide a simple tutorial that mirrors the 'Four Days on Rails' ToDo application. It's a work in progress at the moment.
It is assumed that the reader has been through the official tutorial and has set up their own project. The ToDo application will be a new app within the project.
Change to your project directory and run your manage.py:
/myProject $ ./manage.py startapp ToDo /myProject $ cd ToDo/ /myProject $ ls -R .: __init__.py models views.py ./models: ToDo.py __init__.py /myProject $
Django has created the models directory for us so let's define some models (vim Todo/models/ToDo.py).
from django.core import meta class Category(meta.Model): category = meta.CharField(maxlength=20, unique=True) createdOn = meta.DateField(auto_now_add=True) modifiedOn = meta.DateField(auto_now=True) def __repr__(self): return "%s" % (self.category,) class META: admin = meta.Admin()
unique=True will ensure that we cannot have two categories the same; auto_now_add will set the createdOn field when a Category is added but leave it alone otherwise; and auto_now will set the modifiedOn field whenever the Category is updated. We'll use manage.py to install the app but first make sure to add the application to your INSTALLED_APPS:
INSTALLED_APPS = ( 'myProject.Todo', 'django.contrib.admin', )
Install the app with ./manage.py install ToDo. The Rails tutorial now shows us the beauty of Scaffolding and validation but Django 'comes with the whole house' in the form of the admin app and our validation is already sorted by the maxlength and unique constraints we added in the model's definition. Rather than show the magic again let's get on with some actually development (after a quick recap).
So far we've defined a new model and added it to the database. Django has generated the required SQL and automatically performs validation based on the constraints we set up. If the admin application is installed then we could play around with these features and marvel at the 'whole house' functionality we got for free.
Lines of code so far: 9 (model + INSTALLED_APP)
Once the magic of Scaffolding has worn off the next step in Rails development is to run scaffold as a script and get a load of files generated for you. They deal with the controllers for the various tables you've spent _ages_ writting the SQL for. Things are a little different in Django. The majority of the second day of the Rails tutorial is spent inspecting the scaffold code used to generate the CRUD views for the Category model. Django's got this all covered with the admin app; we don't need to set up our own views and can just concentrate on the application we want to develop.
To be continued...