Writing your first Django app, part 2Âś
This tutorial begins where Tutorial 1 left off. Weâre continuing the Web-poll application and will focus on Djangoâs automatically-generated admin site.
Philosophy
Generating admin sites for your staff or clients to add, change and delete content is tedious work that doesnât require much creativity. For that reason, Django entirely automates creation of admin interfaces for models.
Django was written in a newsroom environment, with a very clear separation between âcontent publishersâ and the âpublicâ site. Site managers use the system to add news stories, events, sports scores, etc., and that content is displayed on the public site. Django solves the problem of creating a unified interface for site administrators to edit content.
The admin isnât intended to be used by site visitors. Itâs for site managers.
Creating an admin userÂś
First weâll need to create a user who can login to the admin site. Run the following command:
$ python manage.py createsuperuser
Enter your desired username and press enter.
Username: admin
You will then be prompted for your desired email address:
Email address: admin@example.com
The final step is to enter your password. You will be asked to enter your password twice, the second time as a confirmation of the first.
Password: **********
Password (again): *********
Superuser created successfully.
Start the development serverÂś
The Django admin site is activated by default. Letâs start the development server and explore it.
Recall from Tutorial 1 that you start the development server like so:
$ python manage.py runserver
Now, open a Web browser and go to â/admin/â on your local domain â e.g., http://127.0.0.1:8000/admin/. You should see the adminâs login screen:

Since translation is turned on by default, the login screen may be displayed in your own language, depending on your browserâs settings and on whether Django has a translation for this language.
Doesnât match what you see?
If at this point, instead of the above login page, you get an error page reporting something like:
ImportError at /admin/
cannot import name patterns
...
then youâre probably using a version of Django that doesnât match this tutorial version. Youâll want to either switch to the older tutorial or the newer Django version.
Enter the admin siteÂś
Now, try logging in with the superuser account you created in the previous step. You should see the Django admin index page:

You should see a few types of editable content: groups and users. They are
provided by django.contrib.auth
, the authentication framework shipped
by Django.
Make the poll app modifiable in the adminÂś
But whereâs our poll app? Itâs not displayed on the admin index page.
Just one thing to do: we need to tell the admin that Question
objects have an admin interface. To do this, open the polls/admin.py
file, and edit it to look like this:
from django.contrib import admin
from .models import Question
admin.site.register(Question)
Explore the free admin functionalityÂś
Now that weâve registered Question
, Django knows that it should be displayed on
the admin index page:

Click âQuestionsâ. Now youâre at the âchange listâ page for questions. This page displays all the questions in the database and lets you choose one to change it. Thereâs the âWhatâs up?â question we created in the first tutorial:

Click the âWhatâs up?â question to edit it:

Things to note here:
- The form is automatically generated from the
Question
model. - The different model field types (
DateTimeField
,CharField
) correspond to the appropriate HTML input widget. Each type of field knows how to display itself in the Django admin. - Each
DateTimeField
gets free JavaScript shortcuts. Dates get a âTodayâ shortcut and calendar popup, and times get a âNowâ shortcut and a convenient popup that lists commonly entered times.
The bottom part of the page gives you a couple of options:
- Save â Saves changes and returns to the change-list page for this type of object.
- Save and continue editing â Saves changes and reloads the admin page for this object.
- Save and add another â Saves changes and loads a new, blank form for this type of object.
- Delete â Displays a delete confirmation page.
If the value of âDate publishedâ doesnât match the time when you created the
question in Tutorial 1, it probably means you forgot to set the correct value for
the TIME_ZONE
setting. Change it, reload the page and check that
the correct value appears.
Change the âDate publishedâ by clicking the âTodayâ and âNowâ shortcuts. Then click âSave and continue editing.â Then click âHistoryâ in the upper right. Youâll see a page listing all changes made to this object via the Django admin, with the timestamp and username of the person who made the change:

Customize the admin formÂś
Take a few minutes to marvel at all the code you didnât have to write. By
registering the Question
model with admin.site.register(Question)
,
Django was able to construct a default form representation. Often, youâll want
to customize how the admin form looks and works. Youâll do this by telling
Django the options you want when you register the object.
Letâs see how this works by re-ordering the fields on the edit form. Replace
the admin.site.register(Question)
line with:
from django.contrib import admin
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fields = ['pub_date', 'question_text']
admin.site.register(Question, QuestionAdmin)
Youâll follow this pattern â create a model admin object, then pass it as the
second argument to admin.site.register()
â any time you need to change the
admin options for an object.
This particular change above makes the âPublication dateâ come before the âQuestionâ field:

This isnât impressive with only two fields, but for admin forms with dozens of fields, choosing an intuitive order is an important usability detail.
And speaking of forms with dozens of fields, you might want to split the form up into fieldsets:
from django.contrib import admin
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date']}),
]
admin.site.register(Question, QuestionAdmin)
The first element of each tuple in
fieldsets
is the title of the fieldset.
Hereâs what our form looks like now:

You can assign arbitrary HTML classes to each fieldset. Django provides a
"collapse"
class that displays a particular fieldset initially collapsed.
This is useful when you have a long form that contains a number of fields that
arenât commonly used:
from django.contrib import admin
from .models import Question
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question_text']}),
('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
]
admin.site.register(Question, QuestionAdmin)

Customize the admin change listÂś
Now that the Question admin page is looking good, letâs make some tweaks to the âchange listâ page â the one that displays all the questions in the system.
Hereâs what it looks like at this point:

By default, Django displays the str()
of each object. But sometimes itâd be
more helpful if we could display individual fields. To do that, use the
list_display
admin option, which is a
tuple of field names to display, as columns, on the change list page for the
object:
class QuestionAdmin(admin.ModelAdmin):
# ...
list_display = ('question_text', 'pub_date')
Just for good measure, letâs also include the was_published_recently
custom
method from Tutorial 1:
class QuestionAdmin(admin.ModelAdmin):
# ...
list_display = ('question_text', 'pub_date', 'was_published_recently')
Now the question change list page looks like this:

You can click on the column headers to sort by those values â except in the
case of the was_published_recently
header, because sorting by the output
of an arbitrary method is not supported. Also note that the column header for
was_published_recently
is, by default, the name of the method (with
underscores replaced with spaces), and that each line contains the string
representation of the output.
You can improve that by giving that method (in polls/models.py
) a few
attributes, as follows:
class Question(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
For more information on these method properties, see
list_display
.
Edit your polls/admin.py
file again and add an improvement to the
Question
change list page: filters using the
list_filter
. Add the following line to
QuestionAdmin
:
list_filter = ['pub_date']
That adds a âFilterâ sidebar that lets people filter the change list by the
pub_date
field:

The type of filter displayed depends on the type of field youâre filtering on.
Because pub_date
is a DateTimeField
, Django
knows to give appropriate filter options: âAny date,â âToday,â âPast 7 days,â
âThis month,â âThis year.â
This is shaping up well. Letâs add some search capability:
search_fields = ['question_text']
That adds a search box at the top of the change list. When somebody enters
search terms, Django will search the question_text
field. You can use as many
fields as youâd like â although because it uses a LIKE
query behind the
scenes, limiting the number of search fields to a reasonable number will make
it easier for your database to do the search.
Nowâs also a good time to note that change lists give you free pagination. The
default is to display 100 items per page. Change list pagination
, search boxes
, filters
, date-hierarchies
, and
column-header-ordering
all work together like you think they should.
Customize the admin look and feelÂś
Clearly, having âDjango administrationâ at the top of each admin page is ridiculous. Itâs just placeholder text.
Thatâs easy to change, though, using Djangoâs template system. The Django admin is powered by Django itself, and its interfaces use Djangoâs own template system.
Customizing your projectâs templatesÂś
Create a templates
directory in your project directory (the one that
contains manage.py
). Templates can live anywhere on your filesystem that
Django can access. (Django runs as whatever user your server runs.) However,
keeping your templates within the project is a good convention to follow.
Open your settings file (mysite/settings.py
, remember) and add a
DIRS
option in the TEMPLATES
setting:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DIRS
is a list of filesystem directories to check
when loading Django templates; itâs a search path.
Now create a directory called admin
inside templates
, and copy the
template admin/base_site.html
from within the default Django admin
template directory in the source code of Django itself
(django/contrib/admin/templates
) into that directory.
Where are the Django source files?
If you have difficulty finding where the Django source files are located on your system, run the following command:
$ python -c "
import sys
sys.path = sys.path[1:]
import django
print(django.__path__)"
Then, just edit the file and replace
{{ site_header|default:_('Django administration') }}
(including the curly
braces) with your own siteâs name as you see fit. You should end up with
a section of code like:
{% block branding %}
<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>
{% endblock %}
We use this approach to teach you how to override templates. In an actual
project, you would probably use
the django.contrib.admin.AdminSite.site_header
attribute to more easily
make this particular customization.
This template file contains lots of text like {% block branding %}
and {{ title }}
. The {%
and {{
tags are part of Djangoâs
template language. When Django renders admin/base_site.html
, this
template language will be evaluated to produce the final HTML page.
Donât worry if you canât make any sense of the template right now â
weâll delve into Djangoâs templating language in Tutorial 3.
Note that any of Djangoâs default admin templates can be overridden. To
override a template, just do the same thing you did with base_site.html
â
copy it from the default directory into your custom directory, and make
changes.
Customizing your applicationâs templatesÂś
Astute readers will ask: But if DIRS
was empty by
default, how was Django finding the default admin templates? The answer is
that, since APP_DIRS
is set to True
,
Django automatically looks for a templates/
subdirectory within each
application package, for use as a fallback (donât forget that
django.contrib.admin
is an application).
Our poll application is not very complex and doesnât need custom admin templates. But if it grew more sophisticated and required modification of Djangoâs standard admin templates for some of its functionality, it would be more sensible to modify the applicationâs templates, rather than those in the project. That way, you could include the polls application in any new project and be assured that it would find the custom templates it needed.
See the template loading documentation for more information about how Django finds its templates.
Customize the admin index pageÂś
On a similar note, you might want to customize the look and feel of the Django admin index page.
By default, it displays all the apps in INSTALLED_APPS
that have been
registered with the admin application, in alphabetical order. You may want to
make significant changes to the layout. After all, the index is probably the
most important page of the admin, and it should be easy to use.
The template to customize is admin/index.html
. (Do the same as with
admin/base_site.html
in the previous section â copy it from the default
directory to your custom template directory.) Edit the file, and youâll see it
uses a template variable called app_list
. That variable contains every
installed Django app. Instead of using that, you can hard-code links to
object-specific admin pages in whatever way you think is best. Again,
donât worry if you canât understand the template language â weâll cover that
in more detail in Tutorial 3.
When youâre comfortable with the admin site, read part 3 of this tutorial to start working on public poll views.