Easy Tutorial
❮ Django Middleware Django Install ❯

Django Admin Management Tool

Django provides a web-based administration tool.

The Django automatic administration tool is part of django.contrib. You can see it in the INSTALLED_APPS in your project's settings.py:

/HelloWorld/HelloWorld/settings.py File Code:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

django.contrib is a large set of features, which is part of Django's core code.


Activating the Admin Tool

Usually, it is set up automatically in urls.py when generating the project, and we just need to uncomment it.

The configuration is as follows:

/HelloWorld/HelloWorld/urls.py File Code:

# urls.py
from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

Once this is configured, the Django administration tool can run.


Using the Admin Tool

Start the development server and then visit http://127.0.0.1:8000/admin/ in your browser to see the following interface:

You can create a superuser with the command python manage.py createsuperuser, as shown below:

# python manage.py createsuperuser
Username (leave blank to use 'root'): admin
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.
[root@solar HelloWorld]#

After entering the username and password, you will see the interface below:

To enable the admin interface to manage a data model, we need to register the model with the admin. For example, we previously created the model Test in TestModel. Modify TestModel/admin.py:

HelloWorld/TestModel/admin.py: File Code:

from django.contrib import admin
from TestModel.models import Test

# Register your models here.
admin.site.register(Test)

Refresh the page to see the Testmodel data table:


Complex Models

The admin page is powerful and fully capable of handling more complex data models.

First, add a more complex data model in TestModel/models.py:

HelloWorld/TestModel/models.py: File Code:

from django.db import models

# Create your models here.
class Test(models.Model):
    name = models.CharField(max_length=20)

class Contact(models.Model):
    name   = models.CharField(max_length=200)
    age    = models.IntegerField(default=0)
    email  = models.EmailField()
    def __unicode__(self):
        return self.name

class Tag(models.Model):
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE,)
    name    = models.CharField(max_length=50)
    def __unicode__(self):
        return self.name

Here, there are two tables. Tag has a foreign key to Contact. A Contact can correspond to multiple Tag entries. We can also see many attribute types that were not previously seen, such as IntegerField for storing integers.

Register multiple models and display them in TestModel/admin.py:

HelloWorld/TestModel/admin.py: File code:

from django.contrib import admin
from TestModel.models import Test, Contact, Tag

# Register your models here.
admin.site.register([Test, Contact, Tag])

Refresh the admin page, and the display results are as follows:

With the above admin tools, we can perform complex model operations.

>

If you have not yet created the table structure, you can use the following commands to create it:

$ python manage.py makemigrations TestModel  # Inform Django that we have made some changes to our models
$ python manage.py migrate TestModel   # Create the table structure

Customizing Forms

We can customize the admin page to replace the default page. For example, the "add" page above. We want to display only the name and email sections. Modify TestModel/admin.py:

HelloWorld/TestModel/admin.py: File code:

from django.contrib import admin
from TestModel.models import Test, Contact, Tag

# Register your models here.
class ContactAdmin(admin.ModelAdmin):
    fields = ('name', 'email')

admin.site.register(Contact, ContactAdmin)
admin.site.register([Test, Tag])

The above code defines a ContactAdmin class to specify the display format of the admin page.

The fields attribute defines the fields to be displayed.

Since this class corresponds to the Contact data model, we need to register them together. The display effect is as follows:

We can also divide the input fields into blocks, and each block can define its own format. Modify TestModel/admin.py to:

HelloWorld/TestModel/admin.py: File code:

from django.contrib import admin
from TestModel.models import Test, Contact, Tag

# Register your models here.
class ContactAdmin(admin.ModelAdmin):
    fieldsets = (
        ['Main', {
            'fields': ('name', 'email'),
        }],
        ['Advance', {
            'classes': ('collapse',),  # CSS
            'fields': ('age',),
        }]
    )

admin.site.register(Contact, ContactAdmin)
admin.site.register([Test, Tag])

The above sections are divided into Main and Advance. The classes specify the CSS format of the section. Here, the Advance section is hidden:

The Advance section has a Show button next to it for expansion, and after expanding, you can click Hide to hide it, as shown in the following image:


Inline Display

The above Contact is an external key to Tag, so there is a foreign key relationship.

In the default page display, the two are separated, and the subordinate relationship between them cannot be reflected. We can use inline display to show Tag attached to the Contact's edit page.

Modify TestModel/admin.py:

HelloWorld/TestModel/admin.py: File code:

from django.contrib import admin
from TestModel.models import Test, Contact, Tag

# Register your models here.
class TagInline(admin.TabularInline):
    model = Tag

class ContactAdmin(admin.ModelAdmin):
    inlines = [TagInline]  # Inline

admin.site.register(Contact, ContactAdmin)
admin.site.register([Test, Tag])
fieldsets = (
    ['Main', {
        'fields': ('name', 'email'),
    }],
    ['Advance', {
        'classes': ('collapse',),
        'fields': ('age',),
    }]
)

admin.site.register(Contact, ContactAdmin)
admin.site.register([Test])

The display looks like this:


Display on the List Page

After entering several records in Contact, the list page for Contact looks like this:

We can also customize the display of this page, such as showing more columns in the list, by adding the list_display attribute in ContactAdmin:

HelloWorld/TestModel/admin.py: File Code:

from django.contrib import admin
from TestModel.models import Test, Contact, Tag

# Register your models here.
class TagInline(admin.TabularInline):
    model = Tag

class ContactAdmin(admin.ModelAdmin):
    list_display = ('name', 'age', 'email')  # list
    inlines = [TagInline]  # Inline
    fieldsets = (
        ['Main', {
            'fields': ('name', 'email'),
        }],
        ['Advance', {
            'classes': ('collapse',),
            'fields': ('age',),
        }]
    )

admin.site.register(Contact, ContactAdmin)
admin.site.register([Test])

Refreshing the page shows the following:

The search function is very useful when managing a large number of records. We can add a search bar to this list page by using search_fields:

HelloWorld/TestModel/admin.py: File Code:

from django.contrib import admin
from TestModel.models import Test, Contact, Tag

# Register your models here.
class TagInline(admin.TabularInline):
    model = Tag

class ContactAdmin(admin.ModelAdmin):
    list_display = ('name', 'age', 'email')  # list
    search_fields = ('name',)
    inlines = [TagInline]  # Inline
    fieldsets = (
        ['Main', {
            'fields': ('name', 'email'),
        }],
        ['Advance', {
            'classes': ('collapse',),
            'fields': ('age',),
        }]
    )

admin.site.register(Contact, ContactAdmin)
admin.site.register([Test])

In this example, we searched for records with the name 'tutorialpro', and the results are displayed as follows:

Django Admin tool has many more practical features. Interested students can explore them further. ```

❮ Django Middleware Django Install ❯