Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Django 3 Web Development Cookbook
  • Toc
  • feedback
Django 3 Web Development Cookbook

Django 3 Web Development Cookbook

By : Aidas Bendoraitis, Jake Kronika
3.6 (9)
close
Django 3 Web Development Cookbook

Django 3 Web Development Cookbook

3.6 (9)
By: Aidas Bendoraitis, Jake Kronika

Overview of this book

Django is a web framework for perfectionists with deadlines, designed to help you build manageable medium and large web projects in a short time span. This fourth edition of the Django Web Development Cookbook is updated with Django 3's latest features to guide you effectively through the development process. This Django book starts by helping you create a virtual environment and project structure for building Python web apps. You'll learn how to build models, views, forms, and templates for your web apps and then integrate JavaScript in your Django apps to add more features. As you advance, you'll create responsive multilingual websites, ready to be shared on social networks. The book will take you through uploading and processing images, rendering data in HTML5, PDF, and Excel, using and creating APIs, and navigating different data types in Django. You'll become well-versed in security best practices and caching techniques to enhance your website's security and speed. This edition not only helps you work with the PostgreSQL database but also the MySQL database. You'll also discover advanced recipes for using Django with Docker and Ansible in development, staging, and production environments. By the end of this book, you will have become proficient in using Django's powerful features and will be equipped to create robust websites.
Table of Contents (15 chapters)
close

Creating a model mixin to take care of meta tags

When you optimize your site for search engines, you not only have to use semantic markup for each page, but you also have to include appropriate meta tags. For maximum flexibility, it helps to have a way to define content for common meta tags, specific to objects that have their own detail pages on your website. In this recipe, we will look at how to create a model mixin for the fields and methods related to the keyword, description, author, and copyright meta tags.

Getting ready

As detailed in the previous recipes, make sure that you have the myproject.apps.core package for your mixins. Also, create a directory structure, templates/utils/includes/, under the package, and inside of that, create a meta.html file to store the basic meta tag markup.

How to do it...

Let's create our model mixin:

  1. Make sure to add "myproject.apps.core" to INSTALLED_APPS in the settings, because we want to take the templates directory into account for this module.
  2. Add the following basic meta tag markup to meta_field.html:
{# templates/core/includes/meta_field.html #}
<meta name="{{ name }}" content="{{ content }}" />
  1. Open the models.py file from the core package in your favorite editor, and add the following content:
# myproject/apps/core/models.py
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils.safestring import mark_safe
from django.template.loader import render_to_string


class MetaTagsBase(models.Model):
"""
Abstract base class for generating meta tags
"""
meta_keywords = models.CharField(
_("Keywords"),
max_length=255,
blank=True,
help_text=_("Separate keywords with commas."),
)
meta_description = models.CharField(
_("Description"),
max_length=255,
blank=True,
)
meta_author = models.CharField(
_("Author"),
max_length=255,
blank=True,
)
meta_copyright = models.CharField(
_("Copyright"),
max_length=255,
blank=True,
)

class Meta:
abstract = True

def get_meta_field(self, name, content):
tag = ""
if name and content:
tag = render_to_string("core/includes/meta_field.html",
{
"name": name,
"content": content,
})
return mark_safe(tag)

def get_meta_keywords(self):
return self.get_meta_field("keywords", self.meta_keywords)

def get_meta_description(self):
return self.get_meta_field("description",
self.meta_description)

def get_meta_author(self):
return self.get_meta_field("author", self.meta_author)

def get_meta_copyright(self):
return self.get_meta_field("copyright",
self.meta_copyright)

def get_meta_tags(self):
return mark_safe("\n".join((
self.get_meta_keywords(),
self.get_meta_description(),
self.get_meta_author(),
self.get_meta_copyright(),
)))

How it works...

This mixin adds four fields to the model that extends from it: meta_keywords, meta_description, meta_author, and meta_copyright. The corresponding get_*() methods, used to render the associated meta tags, are also added. Each of these passes the name and appropriate field content to the core get_meta_field() method, which uses this input to return rendered markup based on the meta_field.html template. Finally, a shortcut get_meta_tags() method is provided to generate the combined markup for all of the available metadata at once.

If you use this mixin in a model, such as Idea, which is shown in the Using model mixins recipe at the start of this chapter, you can put the following in the HEAD section of your detail page template to render all of the meta tags at once, as follows:

{% block meta_tags %}
{{ block.super }}
{{ idea.get_meta_tags }}
{% endblock %}

Here, a meta_tags block has been defined in a parent template, and this snippet shows how the child template redefines the block, including the content from the parent first as block.super, and extending it with our additional tags from the idea object. You could also render only a specific meta tag by using something like the following: {{ idea.get_meta_description }}.

As you may have noticed from the models.py code, the rendered meta tags are marked as safe – that is, they are not escaped, and we don't need to use the safe template filter. Only the values that come from the database are escaped, in order to guarantee that the final HTML is well formed. The database data in meta_keywords and other fields will automatically be escaped when we call render_to_string() for the meta_field.html template, because that template does not specify {% autoescape off %} in its content.

See also

  • The Using model mixins recipe
  • The Creating a model mixin to handle creation and modification dates recipe
  • The Creating a model mixin to handle generic relations recipe
  • The Arranging the base.html template recipe in Chapter 4, Templates and JavaScript
bookmark search playlist download font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete