Django 2 by Example
Build powerful and reliable Python web applications from scratch
Antonio Mele
- 526 pages
- English
- ePUB (mobile friendly)
- Available on iOS & Android
Django 2 by Example
Build powerful and reliable Python web applications from scratch
Antonio Mele
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
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...