Categories help organize Blog Posts into different sections such as Technology, Sports, Education and Travel.
Each Blog Post will belong to one Category.
blog/models.py
from django.db import models
class Category(models.Model):
Id = models.AutoField(primary_key=True)
Name = models.CharField(max_length=100)
def __str__(self):
return self.Name
class Meta:
db_table = "BlogCategories"
After creating or modifying a Model, Django must update the database structure.
This is done using Migrations.
python manage.py makemigrations
Django creates a migration file inside the migrations folder.
python manage.py migrate
Django creates the blog_category table inside the MySQL database.
Refresh your MySQL database and verify that the table has been created successfully.
Create Model
↓
makemigrations
↓
Migration File
↓
migrate
↓
Database Table
Whenever you create a new Model or modify an existing Model, execute the following commands:
python manage.py makemigrations
python manage.py migrate
Without these commands, the database will not reflect the changes made in your Model.
By default, newly created Models do not appear in the Django Admin Panel.
We must register the Model before it can be managed through the Admin Panel.
blog/admin.py
from django.contrib import admin
from .models import Category
admin.site.register(Category)
python manage.py createsuperuser
Enter the required details:
Username
Email Address
Password
Confirm Password
python manage.py runserver
http://127.0.0.1:8000/admin/
Registering a Model tells Django that it should be displayed in the Admin Panel.
Without registration, the Model exists in the database but cannot be managed through the Admin Interface.
The Django Admin Panel provides an easy way to insert, update and delete records without creating custom pages.
http://127.0.0.1:8000/admin/
Click on the Categories module.
Enter a Category Name and click Save.
Technology
Education
Sports
Travel
Health
Business
Refresh the BlogCategories table in MySQL and verify that the records have been inserted successfully.
Django allows us to customize the Admin Panel to improve data management and branding.
In this section, we will customize the Category listing and change the Admin Panel title.
Open blog/admin.py.
from django.contrib import admin
from .models import Category
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['Id', 'Name']
search_fields = ['Name']
ordering = ['Name']
Open blog/admin.py.
from django.contrib import admin
admin.site.site_header = "Blog CMS"
admin.site.site_title = "Blog CMS"
admin.site.index_title = "Welcome to Blog CMS"
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
Implement the same functionality covered in today's Blog Project using your News Portal project.