In this post, we will continue our Django tutorial by adding functionality to our category manager app that we are building in Django.
We will disable/hide categories from public view in category application from the admin page.
Overview of what we will be doing
- add a is_active field in the categories table
- display only is_active=True categories to public
Adding A New Field
Add a new field called is_active
in the Categories
model. The field should be a boolean field type. You can add different field types in Django.
#categories/models.py
from django.db import models
class Categories(models.Model):
...
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
Since the model is already registered in admin.py
. Django provides access to the field by migrating the new data field to the database.
#termianl
$ python manage.py makemigrations
$ python manage.py migrate
Running Migrations In Django
The makemigrations
command generates a SQL based on model as a file inside categories/migrations directory.
In this case to alter the already existing table. These files can be used to rollback to the previous state of the database.
And migrate
command is responsible for applying those changes to the database

Thus you can see new field categories table

Retrieve Active Categories
So far we have created a is_active
field in our Category model. Now, all we need to do is to retrieve categories whose is_active field is true. We will use a filter QuerySet
via object manager to filter categories based on the is_active field.
#categories/views.py
...
def index(request):
all_categories = Categories.objects.filter(is_active=True)
context = {'all_categories': all_categories}
return render(request, 'categories/index.html', context)
...
Thus the index page will display only the categories whose is_active field is true. You can change the field value from the admin page.
Wrapping Up
In this series of Django Tutorial, we learnt to build a category manager app. Here is the GitHub link to code for Learning Django by Building Category Manager.
You must be logged in to post a comment.