Saturday 4 April 2015

The first Django project - Activating admin site

This is the continuation of post The first Django project - Initial Setup and woven around the main post is Django docs.

In urls.py, you can find the following mapping for admin.
url(r'^admin/', include(admin.site.urls)),

Therefore, hit URL http://localhost:8080/admin and you will see the following page.

You can login to this admin portal using the credentials set in step 4 of Initial setup post. Once you do login you will see only Groups and Users tables. To add our models to site administration, go to admin.py and add the following lines.
admin.site.register(Poll)
admin.site.register(Choice)

And then do a refresh to see the following page.

I'll leave it to you to explore the free admin functionality. When you click on add in front of Polls,

We can customize admin.py to show four options along with question.
class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 4


class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
        (None, {'fields': ['question']})
    ]
    inlines = [ChoiceInline]


admin.site.register(Poll, PollAdmin)

Now, adding question screen will look as follows.

The list of questions doesn't look nice - (shown below). We need to customize this screen. Therefore, admin.py will be as follows.
from django.contrib import admin
from polls.models import Poll, Choice


class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 4


class PollAdmin(admin.ModelAdmin):
    list_display = ('question', 'pub_date')

    fieldsets = [
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
        (None, {'fields': ['question']})
    ]

    inlines = [ChoiceInline]

    search_fields = ['question']
    list_filter = ['pub_date']
    admin.site.register(Poll, PollAdmin)

And the screen-cap is -

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.

Do you like this article?