Create custom view and page on Django admin


We can customize Django Admin with custom views and pages. Here are the steps to do:

1. Configure Admin URL
Edit urls.py and append new admin views before “admin.site.urls” :

1
2
3
    …
    url(r’^admin/item/$’, ‘products.views.admin_products’),
    url(r’^admin/’, include(admin.site.urls)),

2. Create Django admin custom views
Create new admin function view:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@login_required
def admin_products(request):
    items_list = Item.objects.all()
    paginator = Paginator(items_list, 25)
    page = request.GET.get(‘page’)

    try:
        items = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        items = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        items = paginator.page(paginator.num_pages)

    data = {"items": items}

    return render(request, "products/admin_item.html", data)

3. Create custom django admin templates
We can use default django admin and modify them later for references instead of building new pages from scratch. We can copy it from “django/contrib/admin/templates/admin” and copy it into templates folder.

Files that usually we need to modified :

1
2
3
4
app_index.html
change_form.html
change_list.html
delete_confirmation.html

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.