Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Django 5 By Example - Fifth Edition

You're reading from  Django 5 By Example - Fifth Edition

Product type Book
Published in Apr 2024
Publisher Packt
ISBN-13 9781805125457
Pages 820 pages
Edition 5th Edition
Languages
Author (1):
Antonio Melé Antonio Melé
Profile icon Antonio Melé
Toc

Table of Contents (20) Chapters close

Preface 1. Building a Blog Application 2. Enhancing Your Blog and Adding Social Features 3. Extending Your Blog Application 4. Building a Social Website 5. Implementing Social Authentication 6. Sharing Content on Your Website 7. Tracking User Actions 8. Building an Online Shop 9. Managing Payments and Orders 10. Extending Your Shop 11. Adding Internationalization to Your Shop 12. Building an E-Learning Platform 13. Creating a Content Management System 14. Rendering and Caching Content 15. Building an API 16. Building a Chat Server 17. Going Live 18. Other Books You May Enjoy
19. Index

Creating an administration site for models

Now that the Post model is in sync with the database, we can create a simple administration site to manage blog posts.

Django comes with a built-in administration interface that is very useful for editing content. The Django site is built dynamically by reading the model metadata and providing a production-ready interface for editing content. You can use it out of the box, configuring how you want your models to be displayed in it.

The django.contrib.admin application is already included in the INSTALLED_APPS setting, so you don’t need to add it.

Creating a superuser

First, you will need to create a user to manage the administration site. Run the following command:

python manage.py createsuperuser

You will see the following output. Enter your desired username, email, and password, as follows:

Username (leave blank to use 'admin'): admin
Email address: admin@admin.com
Password: ********
Password (again): ********

Then, you will see the following success message:

Superuser created successfully.

We just created an administrator user with the highest permissions.

The Django administration site

Start the development server with the following command:

python manage.py runserver

Open http://127.0.0.1:8000/admin/ in your browser. You should see the administration login page, as shown in Figure 1.7:

Figure 1.7: The Django administration site login screen

Log in using the credentials of the user you created in the preceding step. You will see the administration site index page, as shown in Figure 1.8:

Figure 1.8: The Django administration site index page

The Group and User models that you can see in the preceding screenshot are part of the Django authentication framework located in django.contrib.auth. If you click on Users, you will see the user you created previously.

Adding models to the administration site

Let’s add your blog models to the administration site. Edit the admin.py file of the blog application and make it look like this; the new lines are highlighted in bold:

from django.contrib import admin
from .models import Post
admin.site.register(Post)

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

Figure 1.9: The Post model of the blog application included in the Django administration site index page

That was easy, right? When you register a model in the Django administration 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 form that Django has generated dynamically for your model, as shown in Figure 1.10:

Figure 1.10: The Django administration site edit form for the Post model

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 success message and the post you just created, as shown in Figure 1.11:

Figure 1.11: The Django administration site list view for the Post model with an added successfully message

Customizing how models are displayed

Now, we will take a look at how to customize the administration site.

Edit the admin.py file of your blog application and change it, as follows. The new lines are highlighted in bold:

from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ['title', 'slug', 'author', 'publish', 'status']

We are telling the Django administration site that the model is registered in the site using a custom class that inherits from ModelAdmin. In this class, we can include information about how to display the model on the administration site and how to interact with it.

The list_display attribute allows you to set the fields of your model that you want to display on the administration object list page. The @admin.register() decorator performs the same function as the admin.site.register() function that you replaced, registering the ModelAdmin class that it decorates.

Let’s customize the admin model with some more options.

Edit the admin.py file of your blog application and change it, as follows. The new lines are highlighted in bold:

from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ['title', 'slug', 'author', 'publish', 'status']
    list_filter = ['status', 'created', 'publish', 'author']
    search_fields = ['title', 'body']
    prepopulated_fields = {'slug': ('title',)}
    raw_id_fields = ['author']
    date_hierarchy = 'publish'
    ordering = ['status', 'publish']

Return to your browser and reload the post list page. Now, it will look like this:

Figure 1.12: The Django administration site custom list view for the Post model

You can see that the fields displayed on the post list page are the ones we specified in the list_display attribute. The list page now includes a right sidebar that allows you to filter the results by the fields included in the list_filter attribute. Filters for ForeignKey fields like author are only displayed in the sidebar if more than one object exists in the database.

A search bar has appeared on the page. This is because we have defined a list of searchable fields using the search_fields attribute. Just below the search bar, there are navigation links to navigate through a date hierarchy; this has been defined by the date_hierarchy attribute. You can also see that the posts are ordered by STATUS and PUBLISH columns by default. We have specified the default sorting criteria using the ordering attribute.

Next, click on the ADD POST link. You will also note some changes here. As you type the title of a new post, the slug field is filled in automatically. You have told Django to prepopulate the slug field with the input of the title field using the prepopulated_fields attribute:

Figure 1.13: The slug model is now automatically prepopulated as you type in the title

Also, the author field is now displayed with a lookup widget, which can be much better than an input selection drop-down when you have thousands of users. This is achieved with the raw_id_fields attribute and it looks like this:

Figure 1.14: The widget to select related objects for the Author field of the Post model

Adding facet counts to filters

Django 5.0 introduces facet filters to the administration site, showcasing facet counts. These counts indicate the number of objects corresponding to each specific filter, making it easier to identify matching objects in the admin changelist view. Next, we are going to make sure facet filters are always displayed for the PostAdmin admin model.

Edit the admin.py file of your blog application and add the following line highlighted in bold:

from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ['title', 'slug', 'author', 'publish', 'status']
    list_filter = ['status', 'created', 'publish', 'author']
    search_fields = ['title', 'body']
    prepopulated_fields = {'slug': ('title',)}
    raw_id_fields = ['author']
    date_hierarchy = 'publish'
    ordering = ['status', 'publish']
    show_facets = admin.ShowFacets.ALWAYS

Create some posts using the administration site and access http://127.0.0.1:8000/admin/blog/post/. The filters should now include total facet counts, as shown in Figure 1.15:

Figure 1.15: Status field filters including facet counts

With a few lines of code, we have customized the way the model is displayed on the administration site. There are plenty of ways to customize and extend the Django administration site; you will learn more about these later in this book.

You can find more information about the Django administration site at https://docs.djangoproject.com/en/5.0/ref/contrib/admin/.

You have been reading a chapter from
Django 5 By Example - Fifth Edition
Published in: Apr 2024 Publisher: Packt ISBN-13: 9781805125457
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime