Reader small image

You're reading from  Django 5 By Example - Fifth Edition

Product typeBook
Published inApr 2024
PublisherPackt
ISBN-139781805125457
Edition5th Edition
Right arrow
Author (1)
Antonio Melé
Antonio Melé
author image
Antonio Melé

Antonio Melé has been crafting Django projects since 2006, for clients spanning multiple industries. He is Engineering Director at Backbase, a leading global fintech firm dedicated to facilitating the digital transformation of financial institutions. He co-founded Nucoro, a digital wealth management platform. In 2009 Antonio founded Zenx IT, a company specialized in developing digital products. He has been working as CTO and consultant for several tech-centric startups. He has also managed development teams building projects for large enterprise clients. He has an MSc in Computer Science from Universidad Pontificia Comillas and completed the Advanced Management Program at MIT Sloan. His father inspired his passion for computers and coding.
Read more about Antonio Melé

Right arrow

Adding Internationalization to Your Shop

In the previous chapter, you added a coupon system to your shop and built a product recommendation engine.

In this chapter, you will learn how internationalization and localization work. By making your application accessible in multiple languages, you can serve a wider range of users. Additionally, by adapting your application to local formatting conventions such as date or number formatting, you improve its usability. By translating and localizing your application, you will make it more intuitive for users from different cultural backgrounds and increase user engagement.

This chapter will cover the following topics:

  • Preparing your project for internationalization
  • Managing translation files
  • Translating Python code
  • Translating templates
  • Using Rosetta to manage translations
  • Translating URL patterns and using a language prefix in URLs
  • Allowing users to switch language
  • Translating models...

Functional overview

Figure 11.1 shows a representation of the views, templates, and functionalities that will be built in this chapter:

Figure 11.1: Diagram of the functionalities built in Chapter 11

In this chapter, you will implement internationalization in your project and translate templates, URLs, and models. You will add language selection links to the header of your site and create language-specific URLs. You will modify the product_list and product_detail views of the shop application to retrieve Category and Product objects by their translated slugs. You will also add a localized postal code field to the form used in the order_create view.

The source code for this chapter can be found at https://github.com/PacktPublishing/Django-5-by-example/tree/main/Chapter11.

All the Python modules used in this chapter are included in the requirements.txt file in the source code that comes with this chapter. You can follow the instructions to install each Python module...

Before you begin: Join our book community on Discord

Give your feedback straight to the author himself and chat to other readers on the book's dedicated Discord server (find the "early-access-fifth-edition" channel under "FEEDBACK AND SUGGESTIONS").

https://packt.link/D5BE

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 and create a product recommendation engine.

This chapter will cover the following points:

  • Creating a coupon system
  • Applying coupons to the shopping cart
  • Applying coupons to orders
  • Creating coupons for Stripe Checkout
  • Storing products that are usually bought together
  • Building a product recommendation engine with Redis

Figure 10.1 shows a representation of the views, templates and functionalities that will be built in this chapter:

Figure 10.1: Diagram of functionalities built in Chapter 10
...

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 and is valid for a specific time frame.

You are going to create a coupon system for your shop. Your coupons will be valid for customers during a certain 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, you 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 your Django project...

Building a recommendation engine

A recommendation engine is a system that predicts the preference or rating that a user would give to an item. The system selects relevant items for a user based on their behavior and the knowledge it has about them. Nowadays, recommendation systems are used in many online services. They help users by selecting the stuff they might be interested in from the vast amount of available data that is irrelevant to them. Offering good recommendations enhances user engagement. E-commerce sites also benefit from offering relevant product recommendations by increasing their average revenue per user.

You are going to create a simple, yet powerful, recommendation engine that suggests products that are usually bought together. You will suggest products based on historical sales, thus identifying products that are usually bought together. You are going to suggest complementary products in two different scenarios:

  • Product detail page: You will display a list of products...

Additional resources

The following resources provide additional information related to the topics covered in this chapter:

Summary

In this chapter, you created a coupon system using Django sessions and integrated it with Stripe. You also built a recommendation engine using Redis to recommend products that are usually purchased together.

The next chapter will give you an insight into the internationalization and localization of Django projects. You will learn how to translate code and manage translations with Rosetta. You will implement URLs for translations and build a language selector. You will also implement model translations using django-parler and you will validate localized form fields using django-localflavor.

Fuzzy translations

When editing translations in Rosetta, you can see a FUZZY column. This is not a Rosetta feature; it is provided by gettext. If the FUZZY flag is active for a translation, it will not be included in the compiled message files. This flag marks translation strings that need to be reviewed by a translator. When .po files are updated with new translation strings, it is possible that some translation strings will automatically be flagged as fuzzy. This happens when gettext finds some msgid that has been slightly modified. gettext pairs it with what it thinks was the old translation and flags it as fuzzy for review. The translator should then review the fuzzy translations, remove the FUZZY flag, and compile the translation file again.

You have translated your project’s interface, but internationalization doesn’t stop there. You can also translate URL patterns, offering custom URLs tailored for each supported language.

URL patterns for internationalization

Django offers internationalization capabilities for URLs. It includes two main features for internationalized URLs:

  • A language prefix in URL patterns: Adding a language prefix to URLs to serve each language version under a different base URL
  • Translated URL patterns: Translating URL patterns so that every URL is different for each language

One reason for translating URLs is to optimize your site for search engines. By adding a language prefix to your patterns, you will be able to index a URL for each language instead of a single URL for all of them. Furthermore, by translating URLs into each language, you will provide search engines with URLs that will rank better for each language.

Adding a language prefix to URL patterns

Django allows you to add a language prefix to your URL patterns. For example, the English version of your site can be served by a path starting with /en/, and the Spanish version under /es/....

Allowing users to switch language

Since you are serving content that is available in multiple languages, you should let your users switch the site’s language. You are going to add a language selector to your site. The language selector will consist of a list of available languages displayed using links.

Edit the shop/base.html template of the shop application and locate the following lines:

<div id="header">
  <a href="/" class="logo">{% translate "My shop" %}</a>
</div>

Replace them with the following code:

<div id="header">
  <a href="/" class="logo">{% translate "My shop" %}</a>
  {% get_current_language as LANGUAGE_CODE %}
  {% get_available_languages as LANGUAGES %}
  {% get_language_info_list for LANGUAGES as languages %}
  <div class="languages">
    <p>{% translate "Language" %}:</p>
    <...

Translating models with django-parler

Django does not include built-in support to translate models. To manage content in multiple languages, you can either develop a custom solution or opt for a third-party module that facilitates model translation. There are several third-party applications available, each employing a unique method for storing and retrieving translations. One of these applications is django-parler. This module provides a very effective approach for translating models and integrates smoothly with Django’s administration site.

django-parler generates a separate database table for each model that contains translations. This table includes all the translated fields and a foreign key for the original object that the translation belongs to. It also contains a language field, since each row stores the content for a single language.

The django-parler package has not received updates for several years. Despite this, many developers continue to use it...

Format localization

To enhance user experience, it’s important to present dates, times, and numbers in formats that align with the user’s locale. Adapting your site to the data formats familiar to users in various regions significantly improves its accessibility. Since Django 5.0, localized formatting of data is always enabled. Django displays numbers and dates using the format of the current locale.

Django tries to use a locale-specific format whenever it outputs a value in a template. Figure 11.16 shows the format localization for decimal numbers in the English and Spanish versions of the site:

Figure 11.16: Format localization in English and Spanish

Decimal numbers in the English version are displayed with a dot separator for decimal places, while in the Spanish version, a comma is used as the separator. This is due to the locale formats specified for the en and es locales by Django. You can take a look at the English formatting configuration at https...

Using django-localflavor to validate form fields

django-localflavor is a third-party module that contains a collection of utilities, such as form fields or model fields, that are specific for each country. It’s very useful for validating local regions, local phone numbers, identity card numbers, social security numbers, and so on. The package is organized into a series of modules named after ISO 3166 country codes. Follow these instructions to set it up:

Install django-localflavor using the following command:

python -m pip install django-localflavor==4.0

Edit the settings.py file of your project and add localflavor to the INSTALLED_APPS setting, as follows:

INSTALLED_APPS = [
    # ...
    'localflavor',
]

You are going to add the United States zip code field so that a valid United States zip code is required to create a new order. Edit the forms.py file of the orders application and make it look like the following:

from django import forms...

Expanding your project using AI

In this section, you are presented with a task to extend your project, accompanied by a sample prompt for ChatGPT to assist you. To engage with ChatGPT, visit https://chat.openai.com/. If this is your first interaction with ChatGPT, you can revisit the Expanding your project using AI section in Chapter 3, Extending Your Blog Application.

In this project example, we have implemented an online shop. We have added orders, payments, and a coupon system. Now, another typical feature of e-commerce platforms is managing shipping costs. Let’s consider adding a weight attribute to products and implementing shipping costs based on the total weight of the items shipped. Use ChatGPT to help you implement shipping costs for products, making them dependent on the product’s weight. Ensure that Stripe charges the correct amount, including the calculated shipping costs. You can use the prompt provided at https://github.com/PacktPublishing/Django-5...

Summary

In this chapter, you learned the basics of the internationalization and localization of Django projects. You marked code and template strings for translation, and you discovered how to generate and compile translation files. You also installed Rosetta in your project to manage translations through a web interface. You translated URL patterns, and you created a language selector to allow users to switch the language of the site. Then, you used django-parler to translate models, and you used django-localflavor to validate localized form fields.

In the next chapter, you will start a new Django project that will consist of an e-learning platform. You will learn how to use model inheritance to implement polymorphism, and you will lay the foundations for a flexible content management system. You will create the application models, and you will learn how to create and apply fixtures to provide initial data for the models. You will build a custom model field and use it in your...

Additional resources

The following resources provide additional information related to the topics covered in this chapter:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Django 5 By Example - Fifth Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805125457
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Antonio Melé

Antonio Melé has been crafting Django projects since 2006, for clients spanning multiple industries. He is Engineering Director at Backbase, a leading global fintech firm dedicated to facilitating the digital transformation of financial institutions. He co-founded Nucoro, a digital wealth management platform. In 2009 Antonio founded Zenx IT, a company specialized in developing digital products. He has been working as CTO and consultant for several tech-centric startups. He has also managed development teams building projects for large enterprise clients. He has an MSc in Computer Science from Universidad Pontificia Comillas and completed the Advanced Management Program at MIT Sloan. His father inspired his passion for computers and coding.
Read more about Antonio Melé