Book Image

Django By Example

By : Antonio Melé
Book Image

Django By Example

By: Antonio Melé

Overview of this book

<p>Django is a powerful Python web framework designed to develop web applications quickly, from simple prototypes to large-scale projects. Django encourages clean, pragmatic design, and provides developers with a comprehensive set of tools to build scalable web applications.</p> <p>This book will walk you through the creation of four professional Django projects, teaching you how to solve common problems and implement best practices.</p> <p>The book begins by showing you how to build a blog application, before moving on to developing a social image bookmarking website, an online shop and an e-learning platform. You will learn how to build a search engine and implement a user activity stream. Furthermore, you will create a recommendation engine, an e-commerce coupon system and a content management system. The book will also teach you how to enhance your applications with AJAX, create RESTful APIs and setup a production environment for your Django projects.</p> <p>After reading this book, you will have a good understanding of how Django works and how to integrate it with other technologies to build practical, advanced, web applications.</p>
Table of Contents (19 chapters)
Django By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating an administration site for your models


Now that we have defined the Post model, we will 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 admin site is built dynamically by reading your 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.

Remember that django.contrib.admin is already included in the INSTALLED_APPS setting of our project and that's why we don't have to add it.

Creating a superuser

First, we need to create a user to manage the admin site. Run the following command:

python manage.py createsuperuser

You will see the following output. Enter your desired username, e-mail, and password:

Username (leave blank to use 'admin'): admin
Email address: [email protected]
Password: ********
Password (again): ********
Superuser created successfully.

The Django administration site

Now, start the development server with the command python manage.py runserver and open http://127.0.0.1:8000/admin/ in your browser. You should see the administration login page, as shown in the following screenshot:

Log in using the credentials of the user you created in the previous step. You will see the admin site index page, as shown in the following screenshot:

The Group and User models you see here are part of the Django authentication framework located in django.contrib.auth. If you click on Users, you will see the user you created before. The Post model of your blog application has a relationship with this User model. Remember, it is a relationship defined by the author field.

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 in 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 on the right of Posts to add a new post. You will see 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 like 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:

Customizing the way models are displayed

Now we are going to see how to customize the admin site. Edit the admin.py file of your blog application and change it into this:

from django.contrib import admin
from .models import Post

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'slug', 'author', 'publish', 
                    'status')
admin.site.register(Post, PostAdmin)

We are telling the Django admin site that our model is registered into the admin site using a custom class that inherits from ModelAdmin. In this class, we can include information about how to display the model in the admin 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 in the admin object list page.

Let's customize the admin model with some more options, using the following code:

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']

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

You can see that the fields displayed on the post list page are the ones you 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. 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 is a bar to navigate quickly 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. You have specified the default order using the ordering attribute.

Now click on the Add post link. You will also see some changes here. As you type the title of a new post, the slug field is filled automatically. We have told Django to prepopulate the slug field with the input of the title field using the prepopulated_fields attribute. Also, now the author field is displayed with a lookup widget that can scale much better than a dropdown select input when you have thousands of users, as shown in the following screenshot:

With a few lines of code, we have customized the way our model is displayed in the admin site. There are plenty of ways to customize and extend the Django administration site. Later in this book, we will cover this further.