Tutorial: Create our models
Posted: March 18th, 2010 | Author: Adam | Filed under: Django, Python, programming | No Comments »So far in the tutorial we’ve started our project, setup the database, enabled the admin interface and now we’re ready to start to define the database for our project, a simple blog.
This is where we will start working with the models.py file in the “main” application directory (blog/main/). The models.py file is a definition file where we tell Django what all of our database models are. Let’s start with some categories for our blog entry.
from django.db import models
from django.contrib import admin
class Category(models.Model):
Name = models.CharField(max_length=255)
def __unicode__(self):
return self.Name
admin.site.register(Category)
Let’s walk through this real quick since this was a lot of code real quickly. The first two lines we are first importing Django’s base class “models”. This is what we’ll subclass all of our models off of. The next line imports the Django admin object which we will use to include our model in Django’s admin interface.
Next we define our model “Category” subclasses it from the Django base class models.Model. Then we define a field in our model called “Name”. This is the name of a category and we assign name an instance of another subclass of a base Django class called “CharField” this is a simple multi-character field with a maximum length of 255 characters. You can find out more about the types of fields in our Quick Reference: Models page.
Next we define a function called __unicode__ in our new Category class. This is a special function which tell’s Django and Python when we want to “print” an instance of this class call this function. This function will return the value “Name” from the object so that a Category with the name “Books” will return “Books” when it is printed out.
The next line “admin.site.register(Category)” will tell Django to add our new model Category to the admin site.
Let’s go ahead and see what this little snippet of code does before moving on. From the console let’s first sync our database again
$ python manage.py syncdb Creating table main_category
Here we see that Django has created a table in our database called main_category. “main” is the name of our application and “category” is the name of our class. Let’s go ahead and run the development server again and just keep it running in the background this time. It will reload automatically when files in your project and application are changed so I won’t remind you anymore to run the development server past this point in the tutorial
$ python manage.py runserver Validating models... 0 errors found Django version 1.1 alpha 1, using settings 'blog.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
Now let’s go back to the admin interface at http://127.0.0.1:8000/admin/ and see our new model in the admin interface.

We can see our new model “Categorys” in the application “Main” here. Let’s click on “Categorys” (we’ll fix that in a minute) to see how cool the admin interface is.

Let’s click “Add category” in the top right there and create a new category


Now click on our newly created Category “Books” and check out what the Django Admin interface has done for us.

All we’ve done is defined our model and Django has given us a nice CRUD (Create, Edit, Update, Delete) interface for all of data. The admin interface is actually very powerful tool just by itself and anyone who’s developed web applications knows that doing something like for any project takes a huge amount of time. The admin interface is a massive time saver for any project.
Let’s go ahead and fix that “Categorys” typo before we define another model. Let’s look at our models.py file again and add a “Meta” option to our Category class.
class Category(models.Model):
Name = models.CharField(max_length=255)
def __unicode__(self):
return self.Name
class Meta:
verbose_name_plural = "Categories"
admin.site.register(Category)
If the change isn’t that self-explanatory we’ve set the value of verbose_name_plural to the correct plural spelling for “Category”. Django will automatically pluralize models but, sometimes it’s not perfect. It already does so much for us let’s not complain about the small things.
Now let’s define our second model. This is for our blog posts.
from django.contrib.auth.models import User class BlogPost(models.Model): Title = models.CharField(max_length=255) Category = models.ForeignKey(Category) Slug = models.SlugField() Author = models.ForeignKey(User) PostText = models.TextField() PublishDate = models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.Title admin.site.register(BlogPost)
So we should be able to look at this code and begin to figure out what some of it does. The “Title” field is almost identical to our Category -> Name field but, the ForeignKey field is new and worth an explanation. Here we are defining the relationship between a BlogPost and a Category by saying that every BlogPost belongs in some Category. Then we have “SlugField” which is new too. A slug is the URL of a blog post, for example the slug of this blog post is “blog/2010/03/tutorial-create-our-models/”.
Next we have another ForeignKey but, it’s something we haven’t declared. I skipped over the first line in our code up there at first to explain it a bit more in detail here. We imported “from django.contrib.auth.models import User”. This is the “User” class that Django uses. Everyone on our website: admins, authors, commenter, even anonymous users are “Users”. In this line we are saying that every BlogPost has a single author “User”.
Hopefully PostText is self-explanatory so we’ll skip to PublishDate. This is a DateTimeField which not surprisingly stores a Date and a Time. The snippet in the paren’s “auto_now_add=True” means that when the model (the BlogPost) is created the date and time are automatically added instead of being defined by someone.
Let’s resync our database and go back to the admin screen and see what we have now

We see our model “Blog posts” included in our admin. Let’s go into that and write a blog post.

You can see how Django is handling the relationships you’ve defined in your models so far with the “Categories” and “Author” drop downs. Pretty cool huh? This is the real power of the admin interface in Django. It provides a ready made very powerful interface for your database out of the box with very little configuration needed. This admin interface is actually much more powerful that what we’ve covered here.
Go ahead and create another Category and one or two Blog Posts just to get some data into the database for the next part of the tutorial. There we’ll learn about the DB-API and the ORM in Django.
Leave a Reply