Creating an Administration Interface in Django

Exclusive offer: get 50% off this eBook here
Learning Website Development with Django

Learning Website Development with Django — Save 50%

A beginner's tutorial to building web applications, quickly and cleanly, with the Django application framework

$23.99    $12.00
by Ayman Hourieh | January 2009 | Content Management Open Source

We need an administration interface to manage the content that users post to our website. In fact, the administration interface is a universal feature needed in any web application that stores and manages data. For this reason, Django comes with a fully-fledged administration interface ready to be used. This administration interface is considered one of the coolest features in Django because it's easy to use, yet powerful and flexible.

In this article by Ayman Hourieh, you will learn about:

  • Activating the administration interface
  • Using the administration interface to manage content
  • Customizing the administration interface
  • Assigning permissions to users and groups

Activating the Administration Interface

The administration interface comes as a Django application. To activate it, we will follow a simple procedure that is similar to how we enabled the user authentication system.

The admininistration application is located in the django.contrib.admin package. So the first step is adding the path of this package to the INSTALLED_APPS variable. Open settings.py, locate INSTALLED_APPS and edit it as follows:

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.comments',
'django_bookmarks.bookmarks',
)

Next, run the following command to create the necessary tables for the administration application:

$ python manage.py syncdb

Now we need to make the administration interface accessible from within our site by adding URL entries for it. The administration application defines many views, so manually adding a separate entry for each view can become a tedious task. Therefore, Django provides a shortcut for this. The administration interface defines all of its URL entries in a module located at django.contrib.admin.urls, and we can include these entries in our project under a particular path by using a function called include(). Open urls.py and add the following URL entry to it:

urlpatterns = (
# Admin interface
(r'^admin/', include('django.contrib.admin.urls')),
)

This looks different from how we usually define URL entries. We are basically telling Django to retrieve all of the URL entries in the django.contrib.admin.urls module, and to include them in our application under the path ^admin/. This will make the views of the administration interface accessible from within our project.

One last thing remains before we see the administration page in action. We need to tell Django what models can be managed in the administration interface. This is done by defining a class called Admin inside each model. Open bookmarks/models.py and add the highlighted section to the Link model:

class Link(models.Model):
url = models.URLField(unique=True)
def __str__(self):
return self.url
class Admin:
pass

The Admin class defined inside the model effectively tells Django to enable the Link model in the administration interface. The keyword pass means that the class is empty. Later, we will use this class to customize the administration page, so it won't remain empty.

Do the same to the Bookmark, Tag and SharedBookmark models; append an empty class called Admin to each of them. The User model is provided by Django and therefore we don't have control over it. Fortunately however, it already contains an Admin class so it's available in the administration interface by default.

Next, launch the development server and direct your browser to http://127.0.0.1:8000/admin/. You will be greeted by a login page. Remember we need to create a superuser account after writing the database model. This is the account that you have to use in order to log in:

Creating an Administration Interface in Django

Next, you will see a list of the models that are available to the administration interface. As discussed earlier, only models with a class named Admin inside them will appear on this page:

Creating an Administration Interface in Django

If you click on a model name, you will get a list of the objects that are stored in the database under this model. You can use this page to view or edit a particular object, or to add a new one. The figure below shows the listing page for the Link model.

Creating an Administration Interface in Django

The edit form is generated according to the fields that exist in the model. The Link form, for example, contains a single text field called Url. You can use this form to view and change the URL of a Link object. In addition, the form performs proper validation of fields before saving the object. So if you try to save a Link object with an invalid URL, you will receive an error message asking you to correct the field. The figure below shows a validation error when trying to save an invalid link:

Creating an Administration Interface in Django

Fields are mapped to form widgets according to their type. Date fields are edited using a calendar widget for example, whereas foreign key fields are edited using a list widget, and so on. The figure below shows a calendar widget from the user edit page. Django uses it for date and time fields:

Creating an Administration Interface in Django

As you may have noticed, the administration interface represents models by using the string returned by the __str__ method. It was indeed a good idea to replace the generic strings returned by the default __str__ method with more helpful ones. This greatly helps when working with the administration page, as well as with debugging.

Experiment with the administration pages; try to create, edit and delete objects. Notice how changes made in the administration interface are immediately reflected on the live site. Also, the administration interface keeps track of the actions that you make, and lets you review the history of changes for each object.

This section has covered most of what you need to know in order to use the administration interface provided by Django. This feature is actually one of the main advantages of using Django; you get a fully featured administration interface from writing only a few lines of code!

Next, we will see how to tweak and customize the administration pages. And as a bonus, we will learn more about the permissions system offered by Django.

Learning Website Development with Django A beginner's tutorial to building web applications, quickly and cleanly, with the Django application framework
Published: April 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Customizing the Administration Interface

The administration interface provided by Django is very powerful and flexible. Activating it only takes a couple of minutes, and this will give you a fully featured administration kit for your site. Although the administration application should be sufficient for most needs, Django offers several ways to customize and enhance it. In addition to specifying which models are available in the administration interface, you can also specify how listing pages are presented, and even override the templates used to render the administration pages. So let's learn about these features.

Customizing Listing Pages

As we saw in the previous section, we defined an empty class called Admin in models.py to mark them as available to the administration interface. This class is also useful in customizing several aspects of the administration pages.

Let's learn about this by example. The listing page of bookmarks displays the string representation of each bookmark, as we can see in the figure below:

Creating an Administration Interface in Django

Wouldn't this page be more useful if it displayed the URL, title and owner of the bookmark in separate columns? It turns out that implementing this only requires a single line of code. Edit the Bookmark model in bookmarks/models.py and replace pass in the body of the Admin class with the highlighted line of code below:

class Bookmark(models.Model):
title = models.CharField(maxlength=200)
user = models.ForeignKey(User)
link = models.ForeignKey(Link)
def __str__(self):
return '%s, %s' % (self.user.username, self.link.url)
class Admin:
list_display = ('title', 'link','user')

Now refresh the same page and notice the changes:

Creating an Administration Interface in Django

The table is organized much better now! We simply defined a tuple attribute called list_display in the Admin class of the Bookmark model. This tuple contains the names of fields to be used in the listing page.

There are other attributes that we can define in the Admin class; each one should be defined as a tuple of one or more field names:

  • list_filter: If defined, it creates a sidebar with links that can be used to filter objects according to one or more fields in the model.
  • ordering: The fields that are used to order objects in the listing page. If the field name is preceded by a minus sign, descending order is used instead of ascending order.
  • search_fields: If defined, it creates a search field that can be used to search available objects in the data model according to one or more fields.

Let's utilize each of the above attributes in the bookmark listing page. Again, edit the Bookmark model in bookmark/models.py and append the following highlighted lines:

class Bookmark(models.Model):
title = models.CharField(maxlength=200)
user = models.ForeignKey(User)
link = models.ForeignKey(Link)
def __str__(self):
return '%s, %s' % (self.user.username, self.link.url)
class Admin:
list_display = ('title', 'link', 'user')
list_filter = ('user', )
ordering = ('title', )
search_fields = ('title', )

These new attributes provide the following features:

  • list_filter enables us to filter bookmarks by user.
  • ordering orders bookmarks by title.
  • search_fields allows us to search bookmarks by title.

Now, refresh the bookmark listing page again to see the changes:

Creating an Administration Interface in Django

As you can see, we were able to customize and enhance the bookmark listing page with only a few lines of code. Next, we will learn about customizing the templates used to render administration pages, which will give us even greater control over the administration interface.

Overriding Administration Templates

There are times when you want to change the look and feel of the administration interface, or to move the elements on the various administration pages and rearrange them. Fortunately, the administration interface is flexible enough to do all of the above and more by allowing us to override its templates.

The process of customizing an administration template is simple. First, you copy the template from the administration application folder to your project's templates folder, and then you edit this template and customize it to your liking. The location of the administration templates depends on where Django is installed. Here is a list of the default installation paths of Django under the major operating systems (where X.X is the version of Python on your system):

  • Windows: C:PythonXXLibsite-packagesdjango
  • UNIX and Linux: /usr/lib/pythonX.X/site-packages/django
  • Mac OS X: /Library/Python/X.X/site-packages/django

If you cannot find Django in the default installation path for your operating system, perform a file system search for django-admin.py. You will get multiple hits, but the one that you want will be under the Django installation path, inside a folder called bin.

After locating the Django installation path, open django/contrib/admin/templates/, and you will find the templates used by the administration application. There are many files in this directory, but the most important ones are:

  • admin/base_site.html: This is the base template for the administration interface. All pages inherit from this template.
  • admin/change_list.html: This template generates a list of available objects in a particular model.
  • admin/change_form.html: This template generates a form for adding or editing an object.
  • admin/delete_confirmation.html: This template generates the confirmation page when deleting an object.

Let's try to customize one of these templates. Suppose that we want to change the string "Django administration" located at the top of all admin pages. To do so, create a folder called admin inside the templates folder of our project, and copy admin/base_site.html to it. After that, edit the file to change all instances of "Django" to "Django Bookmarks":

{% extends "admin/base.html" %}
{% load i18n %}
{% block title %}{{ title|escape }} |
{% trans 'Django Bookmarks site admin' %}{% endblock %}
{% block branding %}
<h1 id="site-name">{% trans 'Django Bookmarks administration' %}</h1>
{% endblock %}
{% block nav-global %}{% endblock %}

Refresh the administration interface in your browser to see the changes:

Creating an Administration Interface in Django

The process was pretty simple, wasn't it? Feel free to experiment with other templates. For example, you may want to add a help message to listing or edit pages. The administration templates make use of many advanced features of the Django template system, so if you see a template tag that you are not familiar with, you can refer to the Django documentation.

Learning Website Development with Django A beginner's tutorial to building web applications, quickly and cleanly, with the Django application framework
Published: April 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

 

Users, Groups and Permissions

So far, we have been logged in to the administration interface using the superuser account that we created with manage.py syncdb. In reality however, you may have other trusted users who need access to the administration page. In this section, we will see how to allow other users to use the administration interface, and we will learn more about the Django permissions system in the process.

But before we continue, I want to emphasize this: only trusted users should be given access to the administration pages. The administration interface is a very powerful tool, so only those whom you know well should be granted access to it.

User Permissions

If you don't have users in the database other than the superuser, create a new user account using a registration form. Alternatively, you could use the administration interface itself by clicking on Users and then Add User. Next, return to the users list and click on the name of the newly created user. You will get a form which can be used to edit various aspects of the user account such as name and email information. Under the Permissions section of the edit form, you will find a checkbox labelled Staff status. Enabling this checkbox will let the new user enter the administration interface; however, they won't be able to do much after they login because this checkbox only grants access to the administration area, and it does not give the ability to see or change data models.

To give the new user enough permissions to change data models, you can enable the Superuser status checkbox, which will grant the new user full permission to perform any function that they want. This option makes the account as powerful as the superuser account created by manage.py syncdb.

On the whole however, it's not desirable to grant a user full access to everything. Therefore, Django gives you the ability to have fine control over what users can do through the permissions system. Below the Superuser status checkbox, you will find a list of permissions that you can grant to the user. If you examine this list, you will find that each data model has three types of permissions:

  • Adding an object to the data model
  • Changing an object in the data model
  • Deleting an object from the data model

These permissions are automatically generated by Django for data models that contain an Admin class. Use the arrow button to grant some permissions to the account that we are editing. For example, give the account the ability to add, edit and delete links, tags and bookmarks. Next, log out and then log in to the administration interface again using the new account. You will notice that you will only be able to manage the Link, Tag and Bookmark data models.

Creating an Administration Interface in Django

The permissions section of the user edit page also contains a checkbox called Active. This checkbox can be used as a global switch to enable and disable the account. When unchecked, the user won't be to log in to the main site or the administration area.

Group Permissions

If you have a considerable number of users who share the same permissions, it would be a tedious and error prone task to edit each user's account and assign the same permissions to them. Therefore, Django provides another user management facility; groups. To put it simply, groups are a way of categorizing users who share the same permissions. You can create a group and assign permissions to it. And when you add a user to the group, this user is granted all of the group's permissions.

Creating a group is not any different from other data models. Click Groups on the main page of the administration interface, and then click on Add Group. Next, enter a group name and assign some permissions to the group, and finally, click save.

To add a user to a group, edit the user account, scroll to the Groups section in the edit form, and select whichever group you want to add the user to.

Using Permissions in Views

Although we have only used permissions in the administration interface so far, Django also lets us utilize the permission system while writing views. It is possible to use permissions when programming a view to grant a group of users access to a particular feature or page, such as private content. We will learn about methods that can be used to do so in this section. We won't actually make changes to the code of our application, but feel free to do so if you want to experiment with the methods explained.

If you wanted to check whether a user has a particular permission, you could use the has_perm method on the User object. This method takes a string that represents the permission in the following format:

app.operation_model

app is the name of the application where the model is located; operation is either add, change or delete; and model is the name of the model. For example, to check whether the user can add tags, use:

user.has_perm('bookmarks.add_tag')

And to check if the user can change bookmarks:

user.has_perm('bookmarks.change_bookmark')

Furthermore, Django provides a decorator that can be used to restrict a view to users who have a particular permission. The decorator is called permission_required and it is located in the django.contrib.auth.decorators package.

Using this decorator is similar to how we used the login_required decorator to restrict pages to logged in users. Let's say we want to restrict the bookmark_save_page view (in bookmarks/views.py) to users who have the bookmarks.add_bookmark permission. To do so, we can use the following code:

from django.contrib.auth.decorators import permission_required
@permission_required('bookmarks.add_bookmark', login_url="/login/")
def bookmark_save_page(request):
# [...]

This decorator takes two parameters: the permission to check for, and where to redirect the user if they don't have the required permission.

The question of whether to use the has_perm method or the permission_required decorator depends on the level of control that you want. If you need to control access to a view as a whole, use the permission_required decorator. However, if you need finer control over permissions inside a view, use the has_perm method. These two approaches should be sufficient for any permission-related needs.

Summary

Although this article is relatively short, we learned how to implement a lot of things. This emphasizes the fact that Django lets you do a lot with only a few lines of code. You learned how to utilize Django's powerful administration interface, how to customize it, and how to take advantage of the comprehensive permission system offered by Django.

Here is a quick summary of the features covered in this article

  • Activating the administration interface
    • Adding the django.contrib.admin application to INSTALLED_APPS in settings.py.
    • Running manage.py syncdb to create the administration application tables.
    • Adding URL entries for the administration pages to urls.py.
    • For each model that you want to manage though the administration interface, appending an empty class called Admin to the model class.
  • You can customize listing pages in the administration interface by adding one or more of the following fields to the Admin class: list_display, list_filter, ordering, search_fields.
  • You can check whether a user has a particular permission by using the has_perm method on the User object.
  • You can restrict a view to users who have a particular permission by using the permission_required decorator from the django.contrib.auth.decorators package.

 

If you have read this article you may be interested to view :

About the Author :


Ayman Hourieh

Ayman Hourieh holds a bachelor degree in Computer Science. He joined the engineering team at Google in January 2008. Prior to that, he worked with web application development for more than two years. In addition, he has been contributing to several Open Source projects such as Mozilla Firefox. Ayman also worked as a teaching assistant in Computer Science courses for one year. Even after working with a variety of technologies, Python remains Ayman's favorite programming language. He found Django to be a powerful and flexible Python framework that helps developers to produce high-quality web applications in a short time.

Books From Packt

Django 1.0 Template Development
Django 1.0 Template Development

Building Powerful and Robust Websites with Drupal 6
Building Powerful and Robust Websites with Drupal 6

Expert Python Programming
Expert Python Programming

Alfresco Developer Guide
Alfresco Developer Guide

Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques
Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques

RESTful PHP Web Services
RESTful PHP Web Services

SOA Cookbook
SOA Cookbook

Building Websites with Joomla! 1.5
Building Websites with Joomla! 1.5

 

 

 

 

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
j
3
V
8
n
m
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software