Just like we created the task app, we're now going to create an app for the categories.
$ python manage.py startapp category
Great, the app is now created and we can add it to the list of installed apps:
INSTALLED_APPS = [ ... 'category', ]
Since we now have the app, let's continue by creating the database model. Open up "category/models.py", and add the following content to it:
Class Category(models.Model): title = models.CharField(max_length=255)
Right now, I'm not going to add more fields to it. Let's update the database before we continue:
$ python3 manage.py makemigrations
When you run this command, Django will create some new files for us. The files contains information about the database model we created. It's just a more low level Python script about the SQL. Next, we just need to execute the migration scripts.
$ python3 manage.py migrate
When this is done, a new table (category) should have been created in the database and we're ready to continue.
Let's register this for the admin interface and add a few categories. Inside "category/admin.py", add the following content:
from .models import Category admin.site.register(Category)
If you log in to the admin interface now, you will see that "Categorys" appears in the list. Categorys is definitely not the correct way to write this. But Django automatically pluralize the names, so how can we fix this?
Go back to "category/models.py" and make the following changes:
Class Category(models.Model): title = models.CharField(max_length=255) class Meta: # New, 1 verbose_name_plural = 'Categories' # New, 2
1. To configure the model and some of its behaviour, we can add a Meta class.
2. To set the pluralized name, we add the "verbose_name_plural" property.
If you now go back and refresh, the correct name should be showing.
You've probably also noticed that when you go in to the list of categories, the names of the categories shows like this:
To change this, we can set the class represenation as one of the methods for the database model. Open up category/models.py again, and below the meta class, add this:
def __str__(self): return self.title
What this does is essentially just take the title property, and override the build in __str__ method for the class.
Table of contents
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page