The Automatic Admin Interface – Django Admin Site

Welcome back in today’s event loop on {{ PLP }}, previously we’ve learned about on the Basic Django Search Queries with Pagination with an actual live example for better illustration and observe how exactly it works.

In this event loop, we’re about to discuss the importance and the usage of the automatic admin interface and as I’ve mentioned earlier from our previous discussions about The Ideal Django Project Structures that has built by the Django core developer by itself for us Django developer to easily manage the database without accessing it directly. Awesome right?

Introduction

The Django Admin Site is useful indeed, which means, we can use this as our back-end access control for the database. Though, it’s built for functionality and not for a fancy web-based interface.

Moreover, the Django Admin Site relies upon your Django Models and it’s metadata to automatically create a transaction page with built-in tracking logs that trigger the event each time the CRUD (Create, Read, Update, and Delete) has been executed.

So, prepare your self once again and stay focus because this would be exciting and fun learning with {{ PLP }}.

Getting Started

Besides, as a full-stacked developer, I really appreciate how Django core developer lightened up our heavy loads in building a web-based application that’s really helpful and understand the plight of the developer like you and me not to build such heavy back-end applications from scratch.

Thus, it gives us the time to be more focused on building our own web-based application instead of re-inventing the wheels with notably reliable data security as well.

Meanwhile, I’ll be illustrating once again a step-by-step guide for your learning stage with of course a live demo so you can feel and experience how exactly it works.

In addition, we’re still using our existing database infrastructure to easily keep track the continuous progress of your learning stage with us, so, basically, from our last discussions regarding the Basic Django Search Queries with Pagination.

Step 1: Create Django Super User

First, we need to create a superuser for us to access the Django Admin Site as a first step before we can proceed with the rest.

1
python3 manage.py createsuperuser

You need to navigate to your current Django project directory, for this guide, we’re working on the [email protected]:~/dev# path and then issue the command above and press ENTER.

1
2
3
4
5
Username (leave blank to use 'root'): admin
Email address: support@pinoylearnpython.com
Password:
Password (again):
Superuser created successfully.

Meanwhile, fill up all the required information to create a user in Django using the web console, at this time, we’re directly creating a superuser account to access everything when we login later from the Django Admin Site. Once again, the password characters will not be displayed for your security reason.

Step 2: Register a new ModelAdmin

Now, open the dev/myroot/admin.py to register the ContactUs model so we can manage this from the Django Admin Site.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from django.contrib import admin

# Call myroot properties
from myroot.models import ContactUs


class ContactUsAdmin(admin.ModelAdmin):
    list_display = ('id', 'full_name', 'email',
                    'subject', 'submitted')
    search_fields = ['id', 'full_name', 'email', 'subject', 'message']
    fieldsets = (
        (None, {
            'fields': ('full_name', 'email',
                       'subject', 'message', 'is_deleted',
                       'deleted_date', 'deleted_by')
        }),
    )


admin.site.register(ContactUs, ContactUsAdmin)

To explain, we need to import the django.contrib import admin so we can use the admin.ModelAdmin and the admin.site.register functionalities. Furthermore, the list_display is for the column display and order as well.

In addition, the search_fields values would be the searchable fields when you try to search the row values.

Also, the fieldsets usage is for the CREATE and UPDATE form, whatever the required fields during the Create and Update form must be listed from the fieldsets dictionary, otherwise, it will throw a required field error except for the field with default value as I’ve mentioned earlier.

However, the fieldsets column definition may not be all fields from the Django Models, as a quick check, this is our actual ContactUs model.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ContactUs(models.Model):
    full_name = models.CharField(max_length=75)
    email = models.EmailField(max_length=254)
    subject = models.CharField(max_length=75)
    message = models.TextField()
    submitted = models.DateTimeField(auto_now_add=True)
    is_deleted = models.BooleanField(default=False)
    deleted_date = models.DateField(null=True, blank=True)
    deleted_by = models.PositiveIntegerField(default=0)

    class Meta:
        index_together = ["full_name", "is_deleted"]
        db_table = 'dev_contact_us'
        verbose_name = 'Contact Us'
        verbose_name_plural = 'Contact Us'

Thus, we listed all the columns except for the submitted column. But, why is it that the submitted is not listed? it’s because, it has the default value in which Django will automatically add during the CREATE event.

Step 3: Download the Django Site Admin assets from the Python disk-packages

In the meantime, the Django Admin Site’s default assets such as the CSS, Fonts, Images, and the JavaScripts are NOT by default is loaded when you access the https://dev.pinoylearnpython.com/admin site and by the way, that is the site address for our newly configured Django Admin Site, in which the origin is from the dev/dev/urls.py as we’ve mentioned earlier, just a quick check, this is the actual URL Pattern at the URLS.py.

1
2
3
4
5
from django.contrib import admin

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

Now, head over to your web server’s console and execute the following commands to get the actual directory of which your Django packages installed. If your daphne is still running, press the CTRL + C to end the daphne web service for a while so we can write few commands below.

1
2
3
4
python3
import django
print(django.__file__)
/usr/local/lib/python3.6/dist-packages/django/__init__.py

Here, we issue the Python command to get the actual location of the Django package being installed and navigate using the FileZilla to the following path.

1
/usr/local/lib/python3.6/dist-packages/django/contrib/admin/static/admin

So, in our development web server, we find this admin folder above and then download this entire admin folder to your local PC.

1
/var/www/html/dev.pinoylearnpython.com/public_html/static

Afterward, upload the entire admin folder back to your web server with the new location which is the var/www/html static folder from your web server.

Why do we need to download the entire admin folder for Django Admin Site?

The main reason, why I do this manually is that, for convenient purposes for me as I don’t want every time I will issue a Django command to always get the static collections like the exact Django command below.

1
python3 manage.py collectstatic

Thus, this command will gather all the Images, CSS, and JS properties that you use for your entire Django powered sites. Besides, earlier we configure the NGINX web server to serve the public static folder for this dev project.

1
2
3
location /static/ {
    alias /var/www/html/dev.pinoylearnpython.com/public_html/static/;
  }

So, every static related asset will be uploaded on this public accessible directory and of course for most of the search engines like Google, Yahoo, Bing, etc to easily indexed any images from our site as well.

Finally, upload all the new and modified files to your web server using a FileZilla and make it sure that you have reloaded your daphne web service to implement the changes.

1
daphne -b 172.104.190.249 -p 8000 dev.asgi:application

Now, we can access the Django Administration Site at https://dev.pinoylearnpython.com/admin/ and for now, I can only access it by my self as this is considered a critical control, but I’ll just take a screenshot for you to see and gained the insights.

Indeed, the Django Admin Site is very convenient and easy to manage, as you can see that from the dashboard, every Django apps will be listed like the myroot app to be grouped accordingly and list out all the Django models as long as you register it from the app’s admin.py file.

You can download the source code from our GitHub repositories at https://github.com/pinoylearnpython/dev and stay tuned for any updates.

In the next event loop on {{ PLP }}.

Congratulations!, this is just a simple yet straightforward guide on how we join the Django Models to the Django Admin Site to manage the CRUD operations at the back-end system provided by the Django core developers and supported locally as well.

Thus, there are more exciting features of the Django Admin Site that we will be discussing in the future, although, the web interface looks from the early HTML era, the functionality is the most important that we can fully utilize without the risk of accessing the production database server.

For those who’re not able to successfully launch your Django Admin Site tutorial or you need more clarifications, don’t worry, leave a comment below and I’m happy to help you to succeed.

See you in the next event loop on Using VirtualEnv with Obscured Django Settings.

That’s all, have fun learning with {{ PLP }}.

To help Filipino students to learn Python programming language with Django to enhance their capabilities in developing robust web-based applications with practical and direct to the point tutorials, step-by-step with actual information that I provided for you. Leave a comment below or email me at [email protected], thank you!