From 7090db3c371fb8a5c3e4f8e8d06abef7136f23e1 Mon Sep 17 00:00:00 2001 From: Danielle McLean Date: Tue, 31 Oct 2017 14:51:50 +1100 Subject: [PATCH] Add JSON-LD support to entries too, mostly so Google can understand the site a little better --- entries/models.py | 27 ++++++++++++++++++++++++++ entries/templates/entries/h-entry.html | 3 ++- users/models.py | 6 +++++- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/entries/models.py b/entries/models.py index 821d353..f57e8af 100644 --- a/entries/models.py +++ b/entries/models.py @@ -1,9 +1,11 @@ from django.contrib.auth import get_user_model +from django.contrib.sites.models import Site from django.db import models from django.urls import reverse from itertools import groupby from slugify import slugify from textwrap import shorten +from urllib.parse import urljoin from meta.models import ModelMeta from users.models import Profile @@ -97,6 +99,31 @@ class Entry(ModelMeta, models.Model): def slug(self): return slugify(self.name) + @property + def json_ld(self): + base = 'https://' + Site.objects.get_current().domain + url = urljoin(base, self.url) + + posting = { + '@context': 'http://schema.org', + '@type': 'BlogPosting', + '@id': url, + 'url': url, + 'mainEntityOfPage': url, + 'author': { + '@type': 'Person', + 'url': urljoin(base, self.author.url), + 'name': self.author.name, + }, + 'headline': self.title, + 'description': self.excerpt, + 'datePublished': self.published.isoformat(), + 'dateModified': self.updated.isoformat(), + } + if self.photo: + posting['image'] = (urljoin(base, self.photo.url), ) + return posting + class Meta: verbose_name_plural = 'entries' ordering = ['-published'] diff --git a/entries/templates/entries/h-entry.html b/entries/templates/entries/h-entry.html index 6a8f6f3..b825d9d 100644 --- a/entries/templates/entries/h-entry.html +++ b/entries/templates/entries/h-entry.html @@ -1,4 +1,4 @@ -{% load friendly_url humanize markdown shortlink %}
+{% load friendly_url humanize jsonify markdown shortlink %}
{% if entry.photo %}{% endif %}
{% if entry.name %}

{{ entry.name }}

{% endif %} @@ -32,4 +32,5 @@ {% endfor %}
+
diff --git a/users/models.py b/users/models.py index 40f45b6..dca161d 100644 --- a/users/models.py +++ b/users/models.py @@ -36,6 +36,10 @@ class User(ModelMeta, AbstractUser): # This is gonna need to change if I ever decide to add multiple-user support ;) url = '/' + @property + def name(self): + return '{0} {1}'.format(self.first_name, self.last_name) + def get_absolute_url(self): return self.url @@ -65,7 +69,7 @@ class User(ModelMeta, AbstractUser): '@type': 'Person', '@id': urljoin(base, self.url), 'url': urljoin(base, self.url), - 'name': '{0} {1}'.format(self.first_name, self.last_name), + 'name': self.name, 'email': self.email, 'image': urljoin(base, self.avatar.url), 'givenName': self.first_name,