===================================== Writing your first Django app, part 7 ===================================== This tutorial begins where :doc:`Tutorial 6 ` left off. We're continuing the Web-poll application and will focus on customizing Django's automatically-generated admin site that we first explored in :doc:`Tutorial 2 `. Customize the admin form ======================== 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 reordering the fields on the edit form. Replace the ``admin.site.register(Question)`` line with: .. snippet:: :filename: polls/admin.py 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 class, then pass it as the second argument to ``admin.site.register()`` -- any time you need to change the admin options for a model. This particular change above makes the "Publication date" come before the "Question" field: .. image:: _images/admin07.png :alt: Fields have been reordered 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: .. snippet:: :filename: polls/admin.py 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 :attr:`~django.contrib.admin.ModelAdmin.fieldsets` is the title of the fieldset. Here's what our form looks like now: .. image:: _images/admin08t.png :alt: Form has fieldsets now Adding related objects ====================== OK, we have our Question admin page, but a ``Question`` has multiple ``Choice``\s, and the admin page doesn't display choices. Yet. There are two ways to solve this problem. The first is to register ``Choice`` with the admin just as we did with ``Question``. That's easy: .. snippet:: :filename: polls/admin.py from django.contrib import admin from .models import Choice, Question # ... admin.site.register(Choice) Now "Choices" is an available option in the Django admin. The "Add choice" form looks like this: .. image:: _images/admin09.png :alt: Choice admin page In that form, the "Question" field is a select box containing every question in the database. Django knows that a :class:`~django.db.models.ForeignKey` should be represented in the admin as a ``