Creating an administration site for your models in Django

Django comes with a built-in administration interface that is very useful for editing content. The Django admin site is built dynamically by reading your model metadata and providing a production-ready interface for editing content. You can use it out-of-the-box, configuring how you want your models to be displayed in it.

Remember that django.contrib.admin is already included in the INSTALLED_APPS setting of our project and that’s why we don’t have to add it.

Creating a superuser

First, we need to create a user to manage the admin site. Run the following command:

python3 manage.py createsuperuser

You will see the following output. Enter your desired username, e-mail, and password:

The Django administration site

Now, start the development server with the command python3 manage.py runserver and open http://127.0.0.1:8000/admin/ in your browser. You should see the administration login page, as shown in the following screenshot:

 

 

Log in using the credentials of the user you created in the previous step. You will see the admin site index page, as shown in the following screenshot:

The Group and User models you see here are part of the Django authentication framework located in django.contrib.auth. If you click on Users, you will see the user you created before. The Post model of your blog application has a relationship with this User model. Remember, it is a relationship defined by the author field.

 

Adding your models to the administration site

Let’s add your blog models to the administration site. Edit the admin.py file of your blog application and make it look like this:

Now, reload the admin site in your browser. You should see your Post model in the admin site as follows:

 

When you register a model in the Django admin site, you get a user-friendly interface generated by introspecting your models that allows you to list, edit, create and delete objects in a simple way.

Click on the Add link on the right of Posts to add a new post. You will see the create form that Django has generated dynamically for your model, as shown in the following screenshot:

 

Fill in the form and click on the Save button. You should be redirected to the post list page with a successful message and the post you just created, as shown in the following screenshot:

Leave a Reply