Django 2 by Example
eBook - ePub

Django 2 by Example

Build powerful and reliable Python web applications from scratch

Antonio Mele

Share book
  1. 526 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Django 2 by Example

Build powerful and reliable Python web applications from scratch

Antonio Mele

Book details
Book preview
Table of contents
Citations

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

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Django 2 by Example an online PDF/ePUB?
Yes, you can access Django 2 by Example by Antonio Mele in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in Python. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781788472005
Edition
1

Extending Your Shop

In the previous chapter, you learned how to integrate a payment gateway into your shop. You also learned how to generate CSV and PDF files. In this chapter, you will add a coupon system to your shop. You will learn how internationalization and localization work, and you will build a recommendation engine.
This chapter will cover the following points:
  • 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

Many online shops give out coupons to customers that can be redeemed for discounts on their purchases. An online coupon usually consists of a code that is given to users, valid for a specific time frame. The code can be redeemed one or multiple times.
We are going to create a coupon system for our shop. Our coupons will be valid for clients that enter the coupon in a specific time frame. The coupons will not have any limitations in terms of the number of times they can be redeemed, and they will be applied to the total value of the shopping cart. For this functionality, we will need to create a model to store the coupon code, a valid time frame, and the discount to apply.
Create a new application inside the myshop project using the following command:
python manage.py startapp coupons
Edit the settings.py file of myshop and add the application to the INSTALLED_APPS setting as follows:
INSTALLED_APPS = [
# ...
'coupons.apps.CouponsConfig',
]
The new application is now active in our Django project.

Building the coupon models

Let's start by creating the Coupon model. Edit the models.py file of the coupons application and add the following code to it:
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
This is the model that we are going to use to store coupons. The Coupon model contains the following fields:
  • 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.
Run the following command to generate the initial migration for the coupons application:
python manage.py makemigrations
The output should include the following lines:
Migrations for 'coupons': 
coupons/migrations/0001_initial.py:
- Create model Coupon
Then, we execute the next command to apply migrations:
python manage.py migrate
You should see an output that includes the following line:
Applying coupons.0001_initial... OK
The migrations are now applied in the database. Let's add the Coupon model to the administration site. Edit the admin.py file of the coupons application and add the following code to it:
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)
The Coupon model is now registered in the administration site. Ensure that your local server is running with the command python manage.py runserver. Open http://127.0.0.1:8000/admin/coupons/coupon/add/ in your browser. You should see the following form:
Fill in the form to create a new coupon that is valid for the current date and make sure that you check the Active checkbox and click the SAVE button.

Applying a coupon to the shopping cart

We can store new coupons and make queries to retrieve existing coupons. Now we need a way for customers to apply coupons to their purchases. The functionality to apply a coupon would be as follows:
  1. The user adds products to the shopping cart.
  2. The user can enter a coupon code in a form displayed in the shopping cart detail page.
  3. 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.
  4. 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.
  5. When the user places an order, we save the coupon to the given order.
Create a new file inside the coupons application directory and name it forms.py. Add the following code to it:
from django import forms

class CouponApplyForm(forms.Form):
code = forms.CharField()
This is the form that we are going to use for the user to enter a coupon code. Edit the views.py file inside the coupons application and add the following code to it:
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')
The coupon_apply view validates the coupon and stores it in the user's session. We apply the require_POST decorator to this view to restrict it to POST requests. In the view, we perform the following tasks:
  1. We instantiate the CouponApplyForm form using the posted data and we check that the form is valid.
  2. 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