Django Tutorial #4: Admin Panel

Please note that this post may contain affiliate links, and for every purchase you make, at no extra cost to you, a commission fee will be rewarded to me.

Unlike Laravel, Django comes with an admin panel, and it is fairly easy to setup.

Create Superuser

First, we’ll need to create a user who can log into the admin site. Run the following command:

python manage.py createsuperuser

Enter your username, email address and password:

Username: admin
Email address: admin@example.com
Password: **********
Password (again): *********
Superuser created successfully.

Next, start the development server and go to http://127.0.0.1:8000/admin/.

Log in with the username and password you just created.

Troubleshoot

However, if you try creating some entries for the categories, tags or posts, notice that on the list page, the entry index is shown instead of the actual name of the entry.

To fix this problem, we need to make some changes to the models.

blog/models.py

from django.conf import settings
from django.db import models


# Create your models here.
class Category(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField()
    description = models.TextField()

    class Meta:
        verbose_name_plural = "categories"

    def __str__(self):
        return self.name


class Tag(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField()
    description = models.TextField()

    def __str__(self):
        return self.name


class Post(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    tag = models.ManyToManyField(Tag)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    slug = models.SlugField()
    content = models.TextField()
    featured_image = models.ImageField(upload_to='images/')
    is_published = models.BooleanField(default=False)
    is_featured = models.BooleanField(default=False)
    created_at = models.DateField(auto_now=True)

    def __str__(self):
        return self.title

Line 11-12, defines the plural form of “category”, or Django will use “categorys” instead.

Line 14-15, 23-24, 39-40, defines that in the list page, use the name or title column instead of the index column.

After making these changes, refresh the browser again, and then you can see the names of the categories instead of just indices.

Starting from the next section, we’ll begin building the core component of our blogging system. We’ll start with URLs and views.

Next Post: Django Tutorial #5: URLs and Views

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *