Django 2 by Example
eBook - ePub

Django 2 by Example

Build powerful and reliable Python web applications from scratch

Antonio Mele

Condividi libro
  1. 526 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Django 2 by Example

Build powerful and reliable Python web applications from scratch

Antonio Mele

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Django 2 by Example è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Django 2 by Example di Antonio Mele in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in Python. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781788472005
Edizione
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...

Indice dei contenuti