Another app (category) - 30 days of Django

Another app (category) - 30 days of Django

/ #Django


I want to make it possible to have tasks in different categories. So let's add one more Django app.

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:
or similar. This is a named just based on the class name and doesn't tell us anything about which category it is.

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

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.