Categories
Django

Django Admin Panel

In this post, we will learn about Django Admin Panel. We will learn to setup database, create users, assign permissions and manage custom data via admin panel.

Introduction to Django Admin

Django has a built-in admin panel that handles the site management. To log into the admin panel, we need to create a superuser. And to create a superuser we need to setup a database. We can manage users, their roles and other models using the admin interface.

Following steps should be considered to setup Admin login interface in Django.

Step 1: Setup Database

Django uses SQlite database as default. In this post, we will be using SQlite as well.

If you wish to use another database, install the appropriate database bindings and change the following keys in the DATABASES default item to match your database connection:

#settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

By default, INSTALLED_APPS in settings.py contains the following apps, all of which come with Django:

#settings.py
INSTALLED_APPS = [
    'django.contrib.admin',    #contains all the necessary setting for admin inteface
    'django.contrib.auth',    #An authentication system
    'django.contrib.contenttypes',    #A framework for content types. 
    'django.contrib.sessions',    #A session framework
    'django.contrib.messages',    #A messaging framework
    'django.contrib.staticfiles',    #A framework for managing static files
]

These applications are included by default as a convenience for the common case.

Truenary Solutions

Some of these applications make use of at least one database table. So we need to create the tables in the database before we can use them.

To do that, run the following command:

$ python manage.py migrate

Step 2: Create a superuser

Once you have migrated all the tables, django provides easy way to activate admin interface by creating a superuser.

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

$ python manage.py createsuperuser

Enter your desired username and press enter.

You will then be prompted for your desired email address.

The final step is to enter your password. You will be asked to enter your password twice, the second time as a confirmation of the first.

migrate necessary tables for django admin

Superuser is created so you can login django admin site via http://127.0.0.1:8000/admin/.

You should see the admin’s login screen:

djagno admin login

Try logging in with the superuser account you created in the previous step. You should logged in and redirected to the Django admin index page:

default django admin panel

Walkthrough Users and Groups in Admin Panel

You can add users and group those users based on permissions from the admin panel. In Django, user roles can be defined in groups. Groups contain a list of permissions.

Permission is a rule (or restrictions) to view, add, change, delete (Django defaults), or custom rules to objects for a specific user or to a group of users. Django provides some default permissions using django.contrib.auth.

Django comes with a built-in permissions system. It provides a way to assign permissions to specific users and groups of users. You can access permissions from views or templates.

Django users overview

Note: The superuser inherits all the permissions (has_perm will return True).

Register Model in Admin Panel

Django provides an automated way to communicate to model through admin panel. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site.

You just have to register the model in the admin.py file. Let’s start with creating a model and registering it to the admin panel.

step 1: Create an application

terminal:
$ python manage.py startapp blog

Note: The blog application should be added in INSTALLED_APPS in settings.py file otherwise migration command will not include blog app.

#helloworld/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog.apps.BlogConfig',        
]

step 2: Creating a blog post model

In the blog/models.py file we define all objects called Models – this is a place where we will define our blog post.

#blog/models.py
from django.conf import settings
from django.db import models
from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

step 3: Create tables for models

#terminal:
$ python manage.py makemigrations blog
$ python manage.py migrate blog
create blog table

step 4: Register model in admin panel

#blog/admin.py
from django.contrib import admin
from .models import Post

admin.site.register(Post)
Blog app in django admin

Now, you can manage post model from django admin panel.

post model in django admin

Wrapping Up

In this post, we went into detail about Django admin panel. We learned how to setup a database for backend data using SQLite. Then we looked at login into the system using a superuser.

We also looked at assigning permissions to Users via Django admin panel. Finally, we learned about managing custom data models.