Setting Up the Automatic admin Application
The automatic back-end application, or admin, has been described as Django’s “crown jewel.” For anyone who has tired of creating simple “CRUD” (Create, Read, Update, Delete) interfaces for Web applications, it’s a godsend. We get much deeper into the admin in “Customizing the Admin” in Chapter 11, “Advanced Django Programming.” For now, let’s just turn it on and poke around.
Because it’s an optional part of Django, you need to specify in your settings.py file you’re using it—just like you did with your own blog app. Open settings.py and add the following line to the INSTALLED_APPS tuple, just underneath 'django.contrib.auth'.
Every time you add a new application to your project, you should run the syncdb command to make sure the tables it needs have been created in your database. Here we can see adding the admin app to INSTALLED_APPS and running syncdb triggers the creation of one more table in our database:
$ ./manage.py syncdb Creating table django_admin_log Installing index for admin.LogEntry model Loading 'initial_data' fixtures... No fixtures found.
Now that the app is set up, all we need to do is give it a URL so we can get to it. You should have noticed these two lines in your automatically generated urls.py.
# Uncomment this for admin: # (r'^admin/', include('django.contrib.admin.urls')),
Remove the # character from the second line (and you can remove the first, comment-only line at the same time) and save the file. You’ve told Django to load up the default admin site, which is a special object used by the contrib admin application.
Finally, your applications need to tell Django which models should show up for editing in the admin screens. To do so, you simply need to define the default admin site mentioned previously and register your BlogPost model with it. Open the mysite/blog/models.py file, make sure the admin application is imported, and then add a line registering your model at the bottom.
from django.db import models from django.contrib import admin class BlogPost(models.Model): title = models.CharField(max_length=150) body = models.TextField() timestamp = models.DateTimeField() admin.site.register(BlogPost)
This simple use of the admin is the tip of the iceberg; it’s possible to specify many different admin-related options by making a special Admin class for a given model, and then registering the model with that class. We do this shortly, and you also see examples of advanced admin use in later chapters, especially in Parts III, “Django Applications by Example,” and IV, “Advanced Django Techniques and Features.”