Building an Admin Panel with Django Admin in 2021
Tags: django, admin, python
Published: 2021-06-15 17:11:54

---
title: Building an Admin Panel with Django Admin in 2021
published: true
description: 
tags: django, admin, python
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2hbsrzfi9atmcxktmih.png
---

{% youtube VGRbQWbjTLo %}

Admin panels are at the heart of every business operation, be it sales, analytics, user management, and so much more. That said, it isn't easy to find the right tools to help you build robust and scalable systems without spending too much time.

Django admin has been the go-to solution for many developers over the years. It provides a fast, easy-to-use, and highly maintainable framework for building full-stack applications and admin dashboards. These reasons make it a great choice to build admin panels.

To show you how to build admin panels with Django, we will build a dashboard for moderators to manage business reviews. All of this will be built on Postgres and the [Public Yelp dataset](https://www.yelp.com/dataset). 

Here’s a sneak peek of what we’ll be building:


![App in action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0yy0r9huj2nbrdsatws.gif)

Awesome right? Let’s get started!
## Setting up a project
We start by setting up a project. A project is a collection of settings for an instance of Django, which includes a database and app configuration. A project may contain multiple apps, but we are only going to need just one.

To set up a project for our Yelp review dashboard, use your terminal and `cd` into a directory where you’d like to store the project and run the below command:

```sh
django-admin startproject yelp
```

When that’s done, `cd` into the `yelp` directory that was created and start up the server by running the command below:

```sh
python manage.py runserver
```
>The server automatically watches the project for changes, so you don’t need to restart it manually

## Creating an app
In Django, you can have multiple apps inside a project. This means that apps are modular and can be used in multiple projects.

Go ahead and create a `reviews` app that will hold the code for the dashboard by running the below command:
```sh
python manage.py startapp reviews
```
You’ll notice that a `reviews` directory has been created with a couple of files. This is where all the code will go.

## Registering the app and database
Next, we’ll need to let Django know about the `reviews` app we just created. We do this by registering the app.

To register the app, open `yelp/settings.py` file and add `reviews.apps.ReviewsConfig` to the `INSTALLED_APPS` list. After adding this, `INSTALLED_APPS` should look like this:

```py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'reviews.apps.ReviewsConfig',
]
```
When that’s done, move on to configure your database connection in the `DATABASES` dictionary:

```py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'your_database',
        'USER': 'your_database_user',
        'PASSWORD': 'your_database_password',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}
```
Save the changes and run the below command so that Django can set up tables in the database for the app in the `INSTALLED_APPS` list:

```sh
python manage.py migrate
```

The last thing that needs to be done here is to modify the path of the admin dashboard in the `yelp/urls.py` file so that it is mounted on the root path instead of /admin. Update the `urlpatterns` list to:

```py
urlpatterns = [
    path('', admin.site.urls),
]
```

## Creating models
With everything set up, we can continue with creating modes that describe the database layout. Models also show relationships between tables and can be used to specify validation and the widgets that Django will create for the dashboard UI.

We are going to need three models: one for businesses, users, and reviews. To create these, head to `reviews/models.py` and paste the below code:

```py
from django.db import models


# Model for Businesses
class Business(models.Model):
    id = models.CharField(primary_key=True, max_length=100)
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100, null=True)
    city = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    stars = models.FloatField()
    categories = models.TextField(null=True)

    def __str__(self):
        return self.name


# Model for Users
class User(models.Model):
    id = models.CharField(primary_key=True, max_length=100)
    name = models.CharField(max_length=100)
    yelping_since = models.DateTimeField()

    def __str__(self):
        return self.name


# Options of the select widget on the UI
status_choice = (('approved', 'APPROVED'), ('pending',
                 'PENDING'), ('rejected', 'REJECTED'))


# Model for Reviews
class Review(models.Model):
    id = models.CharField(primary_key=True, max_length=100)
    status = models.CharField(
        max_length=10, choices=status_choice, default='pending')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    business = models.ForeignKey(Business, on_delete=models.CASCADE)
    stars = models.IntegerField()
    text = models.TextField()
    date = models.DateTimeField()

    def __str__(self):
        return self.user.name

```
You’ll notice that each class represents a model of a table in the database. Each model has variables that represent the fields. The fields are annotated with their respective field types and validation/relationship where necessary.

Now let’s create migrations for these models. Run the below command to do this:

```sh
python manage.py makemigrations reviews
```
Then apply the migrations
```sh
python manage.py migrate
```
Taking a look at the database, you’ll notice that tables for `reviews_business`, `reviews_user`, and `reviews_review` have been created. **At this point, you can import the yelp dataset**.

>Download the [public Yelp dataset](https://www.yelp.com/dataset) and import it into the `reviews_business`, `reviews_user`, and `reviews_review` tables respectively.

## Taking the app for a spin
Are we ready to take the app for a spin? Not so fast. You’ll need to create an admin user to be able to view the site.

To create an admin user, run the following command and answer the prompt:

```sh
python manage.py createsuperuser
```
Once that’s done, start the server(if you previously closed it) and visit [http://127.0.0.1:8000/](http://127.0.0.1:8000/):


```sh
python manage.py runserver
```

![image showing admin dashboard](https://res.cloudinary.com/confidenceappsmith/image/upload/v1623715696/blogs/Screenshot_2021-06-15_at_1.07.46_AM_j7mlan.png)

After logging in, you’ll notice that none of the models we created is showing up. Let’s fix this in the next section.

## Displaying the reviews app
To make the models from the reviews app visible in the admin panel, you’ll need to register them in the `reviews/admin.py` file.

This is quite easy to do. Add the below code to your `reviews/admin.py` file:

```py
from django.contrib import admin

from .models import Business, Review

admin.site.register(Review)
admin.site.register(Business)
```
Save the file and head back to the browser. Upon reloading, you should now see `Business` under the `Review` app.

![image showing dashboard with review app](https://res.cloudinary.com/confidenceappsmith/image/upload/v1623715779/blogs/Screenshot_2021-06-15_at_1.09.28_AM_xd8gyn.png)

Easy as pie, right?

Play around with the dashboard to see the power of Django. But you’ll notice that the way data is displayed a little off, and we can’t see reviews for each business. Django gives us the room to improve user experience, so let’s do that.


## Customizing the dashboard
We can make the reviews dashboard much better by adding some options to customize it.

Head to the `reviews/admin.py` and **replace its content** with the below code:

```py
from django.contrib import admin
from .models import Business, Review


# A class that displays Reviews in a table form
class ReviewInline(admin.TabularInline):
    model = Review

    # Don't add any extra blank form for new Reviews
    extra = 0


# A class that lets us customize the Business list
class BusinessAdmin(admin.ModelAdmin):
    # Embed reviews in related businesses
    inlines = [ReviewInline]

    # Show the below properties in the Business list
    list_display = ('name', 'city', 'stars', 'categories')

    # Add filters for state and stars
    list_filter = ['stars', 'state']

    # Make the Business list searchable by name
    search_fields = ['name']

    # We don't want ids showing up
    exclude = ('id',)


admin.site.register(Business, BusinessAdmin)

```

Save the file and head to your browser. You’ll immediately notice that you have a much better dashboard experience.

![image showing improved dashboard](https://res.cloudinary.com/confidenceappsmith/image/upload/v1623715837/blogs/Screenshot_2021-06-15_at_1.10.28_AM_lb4gi5.png)

We can further make the dashboard cleaner by removing the annoying `AUTHENTICATION AND AUTHORIZATION` app that shows up by default.

To do this, add these lines to your `reviews/admin.py` file:

```py
# Add this to the top of your file
from django.contrib.auth.models import Group, User

# …previous code goes here

# Add this to the bottom of your file
admin.site.unregister(User)
admin.site.unregister(Group)
```

Save the file and reload your browser. Now we have a super clean functional Django reviews dashboard.

![image of landing page with no auth](https://res.cloudinary.com/confidenceappsmith/image/upload/v1623715869/blogs/Screenshot_2021-06-15_at_1.11.02_AM_e6pfey.png)

## Conclusion
Now that the application is fully built, you can play around with it. This dashboard makes it easy for moderators to search for a business and approve reviews made by users.

Here’s everything in action:

![App in action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0yy0r9huj2nbrdsatws.gif)


And that’s a wrap!

If you found this article helpful, please leave a like and check out our awesome product for building internal tools [appsmith.com](https://appsmith.com?utm_source=blog&utm_medium=direct&utm_content=django-admin&utm_campaign=weeklyblog&utm_term=django-admin)