
Django 2 by Example
Build powerful and reliable Python web applications from scratch
- 526 pages
- English
- ePUB (mobile friendly)
- Available on iOS & Android
About this book
Publisher's Note: This edition from 2018 is outdated and is based on Django 2. A new and updated edition of this book, based on Django 3 and including other related updates, is now available.
Learn Django 2 with four end-to-end projects
Key Features
- Learn Django 2 by building real-world web applications from scratch
- Develop powerful web applications quickly using the best coding practices
- Integrate other technologies into your application with clear, step-by-step explanations and comprehensive example code
Book Description
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.
What you will learn
- Build practical real-world web applications with Django 2
- Use Django 2 with other technologies such as Redis and Celery
- Develop pluggable Django 2 applications
- Create advanced features, optimize your code, and use the cache framework
- Add internationalization to your Django 2 projects
- Enhance the user experience using JavaScript and AJAX
- Add social features to your projects
- Build RESTful APIs for your applications
Who this book is for
If you are a web developer who wants to see how to build professional sites with Django 2, this book is for. You will need a basic knowledge of Python, HTML, and JavaScript, but you don't need to have worked with Django before.
Frequently asked questions
- Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
- Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
Information
Extending Your Shop
- Creating a coupon system to apply discounts
- Adding internationalization to your project
- Using Rosetta to manage translations
- Translating models using django-parler
- Building a product recommendation engine
Creating a coupon system
python manage.py startapp coupons
INSTALLED_APPS = [
# ...
'coupons.apps.CouponsConfig',
]
Building the coupon models
from django.db import models
from django.core.validators import MinValueValidator, \
MaxValueValidator
class Coupon(models.Model):
code = models.CharField(max_length=50,
unique=True)
valid_from = models.DateTimeField()
valid_to = models.DateTimeField()
discount = models.IntegerField(
validators=[MinValueValidator(0),
MaxValueValidator(100)])
active = models.BooleanField()
def __str__(self):
return self.code
- code: The code that users have to enter in order to apply the coupon to their purchase.
- valid_from: The datetime value that indicates when the coupon becomes valid.
- valid_to: The datetime value that indicates when the coupon becomes invalid.
- discount: The discount rate to apply (this is a percentage, so it takes values from 0 to 100). We use validators for this field to limit the minimum and maximum accepted values.
- active: A Boolean that indicates whether the coupon is active.
python manage.py makemigrations
Migrations for 'coupons':
coupons/migrations/0001_initial.py:
- Create model Coupon
python manage.py migrate
Applying coupons.0001_initial... OK
from django.contrib import admin
from .models import Coupon
class CouponAdmin(admin.ModelAdmin):
list_display = ['code', 'valid_from', 'valid_to',
'discount', 'active']
list_filter = ['active', 'valid_from', 'valid_to']
search_fields = ['code']
admin.site.register(Coupon, CouponAdmin)

Applying a coupon to the shopping cart
- The user adds products to the shopping cart.
- The user can enter a coupon code in a form displayed in the shopping cart detail page.
- When a user enters a coupon code and submits the form, we look for an existing coupon with the given code that is currently valid. We have to check that the coupon code matches the one entered by the user that the active attribute is True, and that the current datetime is between the valid_from and valid_to values.
- If a coupon is found, we save it in the user's session and display the cart, including the discount applied to it and the updated total amount.
- When the user places an order, we save the coupon to the given order.
from django import forms
class CouponApplyForm(forms.Form):
code = forms.CharField()
from django.shortcuts import render, redirect
from django.utils import timezone
from django.views.decorators.http import require_POST
from .models import Coupon
from .forms import CouponApplyForm
@require_POST
def coupon_apply(request):
now = timezone.now()
form = CouponApplyForm(request.POST)
if form.is_valid():
code = form.cleaned_data['code']
try:
coupon = Coupon.objects.get(code__iexact=code,
valid_from__lte=now,
valid_to__gte=now,
active=True)
request.session['coupon_id'] = coupon.id
except Coupon.DoesNotExist:
request.session['coupon_id'] = None
return redirect('cart:cart_detail')
- We instantiate the CouponApplyForm form using the posted data and we check that the form is valid.
- If the form is valid, we get the code entered by the user from the form's cleaned_data dictionary. We try to retrieve the Coupon object with the given code. We use the iexact field lookup to perform a case-insensitive exact match. The coupon has to be currently active (active=True) and valid for the current datetime. We use Django's timezone.now() function to get the current time zone-aware datetime and we compare it with the valid_from and valid_to fields performing lte (less than or equal to) and gte (greater than or equa...
Table of contents
- Title Page
- Copyright and Credits
- Dedication
- Packt Upsell
- Contributors
- Preface
- Building a Blog Application
- Enhancing Your Blog with Advanced Features
- Extending Your Blog Application
- Building a Social Website
- Sharing Content in Your Website
- Tracking User Actions
- Building an Online Shop
- Managing Payments and Orders
- Extending Your Shop
- Building an E-Learning Platform
- Rendering and Caching Content
- Building an API
- Going Live
- Other Books You May Enjoy