Django 2 by Example
上QQ阅读APP看书,第一时间看更新

Adding your models to the administration site

Let's add your blog models to the administration site. Edit the admin.py file of your blog application and make it look like this:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Now, reload the admin site in your browser. You should see your Post model on the admin site, as follows:

That was easy, right? When you register a model in the Django admin site, you get a user-friendly interface generated by introspecting your models that allows you to list, edit, create, and delete objects in a simple way.

Click on the Add link beside Posts to add a new post. You will note the create form that Django has generated dynamically for your model, as shown in the following screenshot:

Django uses different form widgets for each type of field. Even complex fields, such as DateTimeField, are displayed with an easy interface, such as a JavaScript date picker.

Fill in the form and click on the SAVE button. You should be redirected to the post list page with a successful message and the post you just created, as shown in the following screenshot: