39,59 €
If you want to learn the entire process of developing professional web applications with Django 2, then this book is for you. You will walk through the creation of four professional Django 2 projects, teaching you how to solve common problems and implement best practices.
You will learn how to build a blog application, a social image bookmarking website, an online shop and an e-learning platform. The book will teach you how to enhance your applications with AJAX, create RESTful APIs and set up a production environment for your Django 2 projects. The book walks you through the creation of real-world applications, solving common problems, and implementing best practices. By the end of this book, you will have a deep understanding of Django 2 and how to build advanced web applications.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 501
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Content Development Editor: Arun NadarTechnical Editor: Prajakta MhatreCopy Editor: Dhanya Baburaj and Safis EditingProject Coordinator: Sheejal ShahProofreader: Safis EditingIndexer: Rekha NairProduction Coordinator: Nilesh Mohite
First published: May 2018
Production reference: 1250518
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78847-248-7
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Antonio Melé is the CTO of Exo Investing and the founder of Zenx IT. Antonio has been developing Django projects since 2006 for clients in several industries. He has been working as the CTO and as a technology consultant for multiple technology-based start-ups, and he has managed development teams building projects for large digital businesses. Antonio holds a master's in computer science from Universidad Pontificia Comillas. His father inspired his passion for computers and programming.
Norbert Máté is a web developer. He started his career back in 2008. His first programming language as a professional web developer was PHP, then he moved on to JavaScript/Node.js and Python/Django/Django REST framework. He is passionate about software architecture, design patterns, and clean code. Norbert was the reviewer of another Django book Django RESTful Web Services by Packt Publishing.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Django 2 by Example
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Building a Blog Application
Installing Django
Creating an isolated Python environment
Installing Django with pip
Creating your first project
Running the development server
Project settings
Projects and applications
Creating an application
Designing the blog data schema
Activating your application
Creating and applying migrations
Creating an administration site for your models
Creating a superuser
The Django administration site
Adding your models to the administration site
Customizing the way models are displayed
Working with QuerySet and managers
Creating objects
Updating objects
Retrieving objects
Using the filter() method
Using exclude()
Using order_by()
Deleting objects
When QuerySets are evaluated
Creating model managers
Building list and detail views
Creating list and detail views
Adding URL patterns for your views
Canonical URLs for models
Creating templates for your views
Adding pagination
Using class-based views
Summary
Enhancing Your Blog with Advanced Features
Sharing posts by email
Creating forms with Django
Handling forms in views
Sending emails with Django
Rendering forms in templates
Creating a comment system
Creating forms from models
Handling ModelForms in views
Adding comments to the post detail template
Adding the tagging functionality
Retrieving posts by similarity
Summary
Extending Your Blog Application
Creating custom template tags and filters
Creating custom template tags
Creating custom template filters
Adding a sitemap to your site
Creating feeds for your blog posts
Adding full-text search to your blog
Installing PostgreSQL
Simple search lookups
Searching against multiple fields
Building a search view
Stemming and ranking results
Weighting queries
Searching with trigram similarity
Other full-text search engines
Summary
Building a Social Website
Creating a social website project
Starting your social website project
Using the Django authentication framework
Creating a login view
Using Django authentication views
Login and logout views
Changing password views
Resetting password views
User registration and user profiles
User registration
Extending the user model
Using a custom user model
Using the messages framework
Building a custom authentication backend
Adding social authentication to your site
Authentication using Facebook
Authentication using Twitter
Authentication using Google
Summary
Sharing Content in Your Website
Creating an image bookmarking website
Building the image model
Creating many-to-many relationships
Registering the image model in the administration site
Posting content from other websites
Cleaning form fields
Overriding the save() method of a ModelForm
Building a bookmarklet with jQuery
Creating a detail view for images
Creating image thumbnails using sorl-thumbnail
Adding AJAX actions with jQuery
Loading jQuery
Cross-Site Request Forgery in AJAX requests
Performing AJAX requests with jQuery
Creating custom decorators for your views
Adding AJAX pagination to your list views
Summary
Tracking User Actions
Building a follower system
Creating many-to-many relationships with an intermediary model
Creating list and detail views for user profiles
Building an AJAX view to follow users
Building a generic activity stream application
Using the contenttypes framework
Adding generic relations to your models
Avoiding duplicate actions in the activity stream
Adding user actions to the activity stream
Displaying the activity stream
Optimizing QuerySets that involve related objects
Using select_related()
Using prefetch_related()
Creating templates for actions
Using signals for denormalizing counts
Working with signals
Application configuration classes
Using Redis for storing item views
Installing Redis
Using Redis with Python
Storing item views in Redis
Storing a ranking in Redis
Next steps with Redis
Summary
Building an Online Shop
Creating an online shop project
Creating product catalog models
Registering catalog models on the admin site
Building catalog views
Creating catalog templates
Building a shopping cart
Using Django sessions
Session settings
Session expiration
Storing shopping carts in sessions
Creating shopping cart views
Adding items to the cart
Building a template to display the cart
Adding products to the cart
Updating product quantities in the cart
Creating a context processor for the current cart
Context processors
Setting the cart into the request context
Registering customer orders
Creating order models
Including order models in the administration site
Creating customer orders
Launching asynchronous tasks with Celery
Installing Celery
Installing RabbitMQ
Adding Celery to your project
Adding asynchronous tasks to your application
Monitoring Celery
Summary
Managing Payments and Orders
Integrating a payment gateway
Creating a Braintree sandbox account
Installing the Braintree Python module
Integrating the payment gateway
Integrating Braintree using Hosted Fields
Testing payments
Going live
Exporting orders to CSV files
Adding custom actions to the administration site
Extending the admin site with custom views
Generating PDF invoices dynamically
Installing WeasyPrint
Creating a PDF template
Rendering PDF files
Sending PDF files by email
Summary
Extending Your Shop
Creating a coupon system
Building the coupon models
Applying a coupon to the shopping cart
Applying coupons to orders
Adding internationalization and localization
Internationalization with Django
Internationalization and localization settings
Internationalization management commands
How to add translations to a Django project
How Django determines the current language
Preparing our project for internationalization
Translating Python code
Standard translations
Lazy translations
Translations including variables
Plural forms in translations
Translating your own code
Translating templates
The {% trans %} template tag
The {% blocktrans %} template tag
Translating the shop templates
Using the Rosetta translation interface
Fuzzy translations
URL patterns for internationalization
Adding a language prefix to URL patterns
Translating URL patterns
Allowing users to switch language
Translating models with django-parler
Installing django-parler
Translating model fields
Integrating translations in the administration site
Creating migrations for model translations
Adapting views for translations
Format localization
Using django-localflavor to validate form fields
Building a recommendation engine
Recommending products based on previous purchases
Summary
Building an E-Learning Platform
Setting up the e-learning project
Building the course models
Registering the models in the administration site
Using fixtures to provide initial data for models
Creating models for diverse content
Using model inheritance
Abstract models
Multi-table model inheritance
Proxy models
Creating the content models
Creating custom model fields
Adding ordering to module and content objects
Creating a CMS
Adding an authentication system
Creating the authentication templates
Creating class-based views
Using mixins for class-based views
Working with groups and permissions
Restricting access to class-based views
Managing course modules and content
Using formsets for course modules
Adding content to course modules
Managing modules and contents
Reordering modules and contents
Using mixins from django-braces
Summary
Rendering and Caching Content
Displaying courses
Adding student registration
Creating a student registration view
Enrolling in courses
Accessing the course contents
Rendering different types of content
Using the cache framework
Available cache backends
Installing Memcached
Cache settings
Adding Memcached to your project
Monitoring Memcached
Cache levels
Using the low-level cache API
Caching based on dynamic data
Caching template fragments
Caching views
Using the per-site cache
Summary
Building an API
Building a RESTful API
Installing Django REST framework
Defining serializers
Understanding parsers and renderers
Building list and detail views
Creating nested serializers
Building custom views
Handling authentication
Adding permissions to views
Creating view sets and routers
Adding additional actions to view sets
Creating custom permissions
Serializing course contents
Summary
Going Live
Creating a production environment
Managing settings for multiple environments
Using PostgreSQL
Checking your project
Serving Django through WSGI
Installing uWSGI
Configuring uWSGI
Installing NGINX
The production environment
Configuring NGINX
Serving static and media assets
Securing connections with SSL
Creating an SSL certificate
Configuring NGINX to use SSL
Configuring our project for SSL
Creating a custom middleware
Creating a subdomain middleware
Serving multiple subdomains with NGINX
Implementing custom management commands
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Django is a powerful Python web framework that encourages rapid development and clean, pragmatic design, offering a relatively shallow learning curve. This makes it attractive to both novice and expert programmers.
This book will guide you through the entire process of developing professional web applications with Django. The book not only covers the most relevant aspects of the framework, but also teaches you how to integrate other popular technologies into your Django projects.
The book will walk you through the creation of real-world applications, solving common problems, and implementing best practices with a step-by-step approach that is easy to follow.
After reading this book, you will have a good understanding of how Django works and how to build practical, advanced web applications.
This book is intended for developers with Python knowledge who wish to learn Django in a pragmatic way. Perhaps you are completely new to Django, or you already know a little but you want to get the most out of it. This book will help you master the most relevant areas of the framework by building practical projects from scratch. You need to have familiarity with programming concepts in order to read this book. Some previous knowledge of HTML and JavaScript is assumed.
Chapter 1, Building a Blog Application, introduces you to the framework by creating a blog application. You will create the basic blog models, views, templates, and URLs to display blog posts. You will learn how to build QuerySets with the Django ORM, and you will configure the Django administration site.
Chapter 2, Enhancing Your Blog with Advanced Features, teaches you how to handle forms and model forms, send emails with Django, and integrate third-party applications. You will implement a comment system for your blog posts and allow your users to share posts via email. The chapter also guides you through the process of creating a tagging system.
Chapter 3, Extending Your Blog Application, explores how to create custom template tags and filters. The chapter also shows you how to use the sitemap framework and create an RSS feed for your posts. You will complete your blog application by building a search engine with PostgreSQL's full-text search capabilities.
Chapter 4, Building a Social Website, explains how to build a social website. You will use the Django authentication framework to create user account views. You will learn how to create a custom user profile model and build social authentication into your project using major social networks.
Chapter 5, Sharing Content in Your Website, teaches you how to transform your social application into an image bookmarking website. You will define many-to-many relationships for models, and you will create an AJAX bookmarklet in JavaScript and integrate it into your project. The chapter shows you how to generate image thumbnails and create custom decorators for your views.
Chapter 6, Tracking User Actions, shows you how to build a follower system for users. You will complete your image bookmarking website by creating a user activity stream application. You will learn how to optimize QuerySets, and you will work with signals. You will integrate Redis into your project to count image views.
Chapter 7, Building an Online Shop, explores how to create an online shop. You will build catalog models, and you will create a shopping cart using Django sessions. You will build a context processor for the shopping cart, and you will learn how to implement sending asynchronous notifications to users using Celery.
Chapter 8, Managing Payments and Orders, explains how to integrate a payment gateway into your shop. You will also customize the administration site to export orders to CSV files, and you will generate PDF invoices dynamically.
Chapter 9, Extending Your Shop, teaches you how to create a coupon system to apply discounts to orders. The chapter shows you how to add internationalization to your project and how to translate models. You will also build a product recommendation engine using Redis.
Chapter 10, Building an E-Learning Platform, guides you through creating an e-learning platform. You will add fixtures to your project, use model inheritance, create custom model fields, use class-based views, and manage groups and permissions. You will create a content management system and handle formsets.
Chapter 11, Rendering and Caching Content, shows you how to create a student registration system and manage student enrollment on courses. You will render diverse course content and you will learn how to use the cache framework.
Chapter 12, Building an API, explores building a RESTful API for your project using the Django REST framework.
Chapter 13, Going Live, shows how to set up a production environment using uWSGI and NGINX, and how to secure it with SSL. The chapter explains how to build a custom middleware and create custom management commands.
To get the most out of this book, it is recommended that you have good working knowledge of Python. You should also be comfortable with HTML and JavaScript. Before reading this book, it is recommended that you read parts 1 to 3 of the official Django documentation tutorial at https://docs.djangoproject.com/en/2.0/intro/tutorial01/.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Django-2-by-Example. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
In this book, you will learn how to build complete Django projects, ready for production use. In case you haven't installed Django yet, you will learn how to do it in the first part of this chapter. This chapter covers how to create a simple blog application using Django. The purpose of this chapter is to get a general idea of how the framework works, understand how the different components interact with each other, and provide you with the skills to easily create Django projects with a basic functionality. You will be guided through the creation of a complete project without elaborating upon all the details. The different framework components will be covered in detail throughout this book.
This chapter will cover the following topics:
Installing Django and creating your first project
Designing models and generating model migrations
Creating an administration site for your models
Working with QuerySet and managers
Building views, templates, and URLs
Adding pagination to list views
Using Django's class-based views
If you have already installed Django, you can skip this section and jump directly to the Creating your first project section. Django comes as a Python package and thus can be installed in any Python environment. If you haven't installed Django yet, the following is a quick guide to install Django for local development.
Django 2.0 requires Python version 3.4 or higher. In the examples for this book, we will use Python 3.6.5. If you're using Linux or macOS X, you probably have Python installed. If you are using Windows, you can download a Python installer at https://www.python.org/downloads/windows/.
If you are not sure whether Python is installed on your computer, you can verify it by typing python in the shell. If you see something like the following, then Python is installed on your computer:
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
If your installed Python version is lower than 3.4, or if Python is not installed on your computer, download Python 3.6.5 from https://www.python.org/downloads/ and install it.
Since you will use Python 3, you don't have to install a database. This Python version comes with a built-in SQLite database. SQLite is a lightweight database that you can use with Django for development. If you plan to deploy your application in a production environment, you should use an advanced database, such as PostgreSQL, MySQL, or Oracle. You can get more information about how to get your database running with Django at https://docs.djangoproject.com/en/2.0/topics/install/#database-installation.
It is recommended that you use virtualenv to create isolated Python environments, so that you can use different package versions for different projects, which is far more practical than installing Python packages system-wide. Another advantage of using virtualenv is that you won't need any administration privileges to install Python packages. Run the following command in your shell to install virtualenv:
pip install virtualenv
After you install virtualenv, create an isolated environment with the following command:
virtualenv my_env
This will create a my_env/ directory, including your Python environment. Any Python libraries you install while your virtual environment is active will go into the my_env/lib/python3.6/site-packages directory.
You can locate the path where Python 3 is installed and use it to create the virtual environment with the following commands:
zenx$ which python3
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
zenx$ virtualenv my_env -p /Library/Frameworks/Python.framework/Versions/3.6/bin/python3
Run the following command to activate your virtual environment:
source my_env/bin/activate
The shell prompt will include the name of the active virtual environment enclosed in parentheses, as follows:
(my_env)laptop:~ zenx$
You can deactivate your environment at any time with the deactivate command.
You can find more information about virtualenv at https://virtualenv.pypa.io/en/latest/.
On top of virtualenv, you can use virtualenvwrapper. This tool provides wrappers that make it easier to create and manage your virtual environments. You can download it from https://virtualenvwrapper.readthedocs.io/en/latest/.
The pip package management system is the preferred method for installing Django. Python 3.6 comes with pip preinstalled, but you can find pip installation instructions at https://pip.pypa.io/en/stable/installing/.
Run the following command at the shell prompt to install Django with pip:
pip install Django==2.0.5
Django will be installed in the Python site-packages/ directory of your virtual environment.
Now, check whether Django has been successfully installed. Run python on a terminal, import Django, and check its version, as follows:
>>> import django
>>> django.get_version()
'2.0.5'
If you get the preceding output, Django has been successfully installed on your machine.
Our first Django project will be building a complete blog. Django provides a command that allows you to create an initial project file structure. Run the following command from your shell:
django-admin startproject mysite
This will create a Django project with the name mysite.
Let's take a look at the project structure generated:
mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py
These files are as follows:
manage.py
: This is a command-line utility used to interact with your project. It is a thin wrapper around the
django-admin.py
tool. You don't need to edit this file.
mysite/
: This is your project directory, which consists of the following files:
__init__.py
: An empty file that tells Python to treat the
mysite
directory as a Python module.
settings.py
: This indicates settings and configuration for your project and contains initial default settings.
urls.py
: This is the place where your URL patterns live. Each URL defined here is mapped to a view.
wsgi.py
: This is the configuration to run your project as a
Web Server Gateway Interface
(
WSGI
) application.
The generated settings.py file contains the project settings, including a basic configuration to use an SQLite 3 database and a list named INSTALLED_APPS, which contains common Django applications that are added to your project by default. We will go through these applications later in the Project settings section.
To complete the project setup, we will need to create the tables in the database required by the applications listed in INSTALLED_APPS. Open the shell and run the following commands:
cd mysite
python manage.py migrate
You will note an output that ends with the following lines:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying sessions.0001_initial... OK
The preceding lines are the database migrations that are applied by Django. By applying migrations, the tables for the initial applications are created in the database. You will learn about the migrate management command in the Creating and applying migrationssection of this chapter.
Django comes with a lightweight web server to run your code quickly, without needing to spend time configuring a production server. When you run the Django development server, it keeps checking for changes in your code. It reloads automatically, freeing you from manually reloading it after code changes. However, it might not notice some actions, such as adding new files to your project, so you will have to restart the server manually in these cases.
Start the development server by typing the following command from your project's root folder:
python manage.py runserver
You should see something like this:
Performing system checks...
System check identified no issues (0 silenced).
May 06, 2018 - 17:17:31
Django version 2.0.5, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Now, open http://127.0.0.1:8000/ in your browser. You should see a page stating that the project is successfully running, as shown in the following screenshot:
The preceding screenshot indicates that Django is running. If you take a look at your console, you will see the GET request performed by your browser:
[06/May/2018 17:20:30] "GET / HTTP/1.1" 200 16348
Each HTTP request is logged in the console by the development server. Any error that occurs while running the development server will also appear in the console.
You can indicate Django to run the development server on a custom host and port or tell it to run your project, loading a different settings file, as follows:
python manage.py runserver 127.0.0.1:8001 \
--settings=mysite.settings
Remember that this server is only intended for development and is not suitable for production use. In order to deploy Django in a production environment, you should run it as a WSGI application using a real web server, such as Apache, Gunicorn, or uWSGI. You can find more information on how to deploy Django with different web servers at https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/.
Chapter 13, Going Live, explains how to set up a production environment for your Django projects.
Let's open the settings.py file and take a look at the configuration of our project. There are several settings that Django includes in this file, but these are only a part of all the Django settings available. You can see all settings and their default values in https://docs.djangoproject.com/en/2.0/ref/settings/.
The following settings are worth looking at:
DEBUG
is a boolean that turns the debug mode
o
f the project
on and off
. If it is set to
True
, Django will display detailed error pages when an uncaught exception is thrown by your application. When you move to a production environment, remember that you have to set it to
False
. Never deploy a site into production with
DEBUG
turned on because you will expose sensitive project-related data.
ALLOWED_HOSTS
is not applied while debug mode is on, or when the tests are run. Once you move your site to production and set
DEBUG
to
False
, you will have to add your domain/host to this setting in order to allow it to serve your Django site.
INSTALLED_APPS
is a setting you will have to edit for all projects. This setting tells Django which applications are active for this site. By default, Django includes the following applications:
django.contrib.admin
: An administration site
django.contrib.auth
: An authentication framework
django.contrib.contenttypes
: A framework for handling content types
django.contrib.sessions
: A session framework
django.contrib.messages
: A messaging framework
django.contrib.staticfiles
: A framework for managing static files
MIDDLEWARE
is a list that contains middleware to be executed.
ROOT_URLCONF
indicates the Python module where the root URL patterns of your application are defined.
DATABASES
is a dictionary that contains the settings for all the databases to be used in the project. There must always be a default database. The default configuration uses an SQLite3 database.
LANGUAGE_CODE
defines the default language code for this Django site.
USE_TZ
tells Django to activate/deactivate timezone support. Django comes with support for timezone-aware datetime.
This setting is set to
True
when you create a new project using the
startproject
management command.
Don't worry if you don't understand much about what you are seeing. You will learn the different Django settings in the following chapters.
Throughout this book, you will encounter the terms project and application over and over. In Django, a project is considered a Django installation with some settings. An application is a group of models, views, templates, and URLs. Applications interact with the framework to provide some specific functionalities and may be reused in various projects. You can think of the project as your website, which contains several applications such as a blog, wiki, or forum, that can be used by other projects also.
Now, let's create our first Django application. We will create a blog application from scratch. From the project's root directory, run the following command:
python manage.py startapp blog
This will create the basic structure of the application, which looks like this:
blog/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py
These files are as follows:
admin.py
: This is where you register models to include them in the Django administration site—using the Django admin site is optional.
apps.py
: This includes the main configuration of the
blog
application.
migrations
: This directory will contain database migrations of your application. Migrations allow Django to track your model changes and synchronize the database accordingly.
models.py
: Data models of your application—all Django applications need to have a
models.py
file, but this file can be left empty.
tests.py
: This is where you can add tests for your application.
views.py
: The logic of your application goes here; each view receives an HTTP request, processes it, and returns a response.
Now that we have a data model for our blog posts, we will need a database table for it. Django comes with a migration system that tracks the changes done to models and allows to propagate them into the database. The migrate command applies migrations for all applications listed in INSTALLED_APPS; it synchronizes the database with the current models and existing migrations.
First, you will need to create an initial migration for our Post model. In the root directory of your project, run the following command:
python manage.py makemigrations blog
You should get the following output:
Migrations for 'blog':
blog/migrations/0001_initial.py
- Create model Post
Django just created the 0001_initial.pyfile inside the migrations directory of the blog application. You can open that file to see how a migration appears. A migration specifies dependencies on other migrations and operations to perform in the database to synchronize it with model changes.
Let's take a look at the SQL code that Django will execute in the database to create the table for our model. The sqlmigrate command takes migration names and returns their SQL without executing it. Run the following command to inspect the SQL output of our first migration:
python manage.py sqlmigrate blog 0001
The output should look as follows:
BEGIN;
--
-- Create model Post
--
CREATE TABLE "blog_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(250) NOT NULL, "slug" varchar(250) NOT NULL, "body" text NOT NULL, "publish" datetime NOT NULL, "created" datetime NOT NULL, "updated" datetime NOT NULL, "status" varchar(10) NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id"));
CREATE INDEX "blog_post_slug_b95473f2" ON "blog_post" ("slug");
CREATE INDEX "blog_post_author_id_dd7a8485" ON "blog_post" ("author_id");
COMMIT;
The exact output depends on the database you are using. The preceding output is generated for SQLite. As you can see in the preceding output, Django generates the table names by combining the app name and the lowercase name of the model (blog_post), but you can also specify a custom database name for your model in the Meta class of the model using the db_table attribute. Django creates a primary key automatically for each model, but you can also override this by specifying primary_key=True in one of your model fields. The default primary key is an id column, which consists of an integer that is incremented automatically. This column corresponds to the id field that is automatically added to your models.
Let's sync our database with the new model. Run the following command to apply existing migrations:
python manage.py migrate
You will get an output that ends with the following line:
Applying blog.0001_initial... OK
We just applied migrations for the applications listed in INSTALLED_APPS, including our blog application. After applying migrations, the database reflects the current status of our models.
If you edit your models.py file in order to add, remove, or change fields of existing models, or if you add new models, you will have to create a new migration using the makemigrations command. The migration will allow Django to keep track of model changes. Then, you will have to apply it with the migrate command to keep the database in sync with your models.
Now that we have defined the Post model, we will create a simple administration site to manage your 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.
The django.contrib.admin application is already included in the INSTALLED_APPS setting, so we don't need to add it.
First, we 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: [email protected]
Password: ********
Password (again): ********
Superuser created successfully.
Now, start the development server with the python manage.py runserver command 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 preceding step. You will see the admin site index page, as shown in the following screenshot:
The Group and User models you 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. The Post model of your blog application has a relationship with this User model. Remember that it is a relationship defined by the author field.
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 adminfrom .models import Postadmin.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:
Now that you have a fully functional administration site to manage your blog's content, it's time to learn how to retrieve information from the database and interact with it. Django comes with a powerful database abstraction API that lets you create, retrieve, update, and delete objects easily. The Django Object-relational mapper is compatible with MySQL, PostgreSQL, SQLite, and Oracle. Remember that you can define the database of your project in the DATABASES setting of your project's settings.py file. Django can work with multiple databases at a time, and you can program database routers to create custom routing schemes.
Once you have created your data models, Django gives you a free API to interact with them. You can find the data model reference of the official documentation at https://docs.djangoproject.com/en/2.0/ref/models/.
To filter a QuerySet, you can use the filter() method of the manager. For example, we can retrieve all posts published in the year 2017 using the following QuerySet:
Post.objects.filter(publish__year=2017)
You can also filter by multiple fields. For example, we can retrieve all posts published in 2017 by the author with the username admin:
Post.objects.filter(publish__year=2017, author__username='admin')
This equates to building the same QuerySet chaining multiple filters:
Post.objects.filter(publish__year=2017) \ .filter(author__username='admin')
You can exclude certain results from your QuerySet using the exclude() method of the manager. For example, we can retrieve all posts published in 2017 whose titles don't start with Why:
Post.objects.filter(publish__year=2017) \ .exclude(title__startswith='Why')
You can order results by different fields using the order_by() method of the manager. For example, you can retrieve all objects ordered by their title, as follows:
Post.objects.order_by('title')
Ascending order is implied. You can indicate descending order with a negative sign prefix, like this:
Post.objects.order_by('
-
title')
You can concatenate as many filters as you like to a QuerySet, and you will not hit the database until the QuerySet is evaluated. QuerySets are only evaluated in the following cases:
The first time you iterate over them
When you slice them, for instance,
Post.objects.all()[:3]
When you pickle or cache them
When you call
repr()
or
len()
on them
When you explicitly call
list()
on them
When you test them in a statement, such as
bool()
,
or
,
and
, or
if
Now that you have knowledge of how to use the ORM, you are ready to build the views of the blog application. A Django view is just a Python function that receives a web request and returns a web response. All the logic to return the desired response goes inside the view.
First, we will create our application views, then we will define a URL pattern for each view, and finally, we will create HTML templates to render the data generated by the views. Each view will render a template passing variables to it and will return an HTTP response with the rendered output.