How to create a basic blog in Django » Configuring the automatic admin

In many of your own applications you will probably want to write your own administration functions, you will completely miss out this section.

Create admin.py in blog folder we created earlier. This admin.py file is automatically checked by django admin for every application defined under INSTALLED_APPS in the settings.py

    from django.contrib import admin
    from blog.models import Blog, Category

    admin.site.register(Blog)
    admin.site.register(Category)

Now lets see what each part means.

Import the command which allows us to register the model we created

    from django.contrib import admin

Import our models

    from blog.models import Blog, Category

Register our models Blog & Category with the admin

    admin.site.register(Blog)
    admin.site.register(Category)

Although these three lines are enough to get the admin working, we want to add a little more functionality. Heres the final admin.py.

    from django.contrib import admin
    from djangorocks.blog.models import Blog, Category

    class BlogAdmin(admin.ModelAdmin):
        exclude = ['posted']
        prepopulated_fields = {'slug': ('title',)}

    class CategoryAdmin(admin.ModelAdmin):
        prepopulated_fields = {'slug': ('title',)}

    admin.site.register(Blog, BlogAdmin)
    admin.site.register(Category, CategoryAdmin)

Now that you have added these models into the admin, you might want to login and add a few categories and blog posts.

Limitations from this example

  • The prepopulated_fields are exactly as they sound. The data for the slug field is automatically populated by the data entered in the to title field. Remember this ONLY works in the django admin so if you are not using this, the slug field will not be populated.
  • The excluded field in this instance again is automatically populated with the date it was created. Remember this ONLY works in the django admin so if you are not using this, the date field will not be populated.

A good way to solve these problems is to update your models with a save function. PROVIDE A LINK TO HINTS & TIPS