schema.org

django-meta provides full support for schema.org in JSON-LD format.

schema.org is supported in both Model support and View support framework.

Model-level

In the same way as basic _metadata attribute, _schema exists to resolve and build the per-object Schema.org representation of the current object.

As per _metadata, _schema values can contains the name of a method, property or attribute available on the class:

class Blog(ModelMeta, Model)
    ...
    _schema = {
        'image': 'get_image_full_url',
        'articleBody': 'text',
        'articleSection': 'get_categories',
        'author': 'get_schema_author',
        'copyrightYear': 'copyright_year',
        'dateCreated': 'get_date',
        'dateModified': 'get_date',
        'datePublished': 'date_published',
        'headline': 'headline',
        'keywords': 'get_keywords',
        'description': 'get_description',
        'name': 'title',
        'url': 'get_full_url',
        'mainEntityOfPage': 'get_full_url',
        'publisher': 'get_site',
    }

View-level

Meta and MetadataMixin provides a few API to work with schema.org properties.

MetadataMixin

The high level interface is meta.views.MetadataMixin.get_schema() which works in much the same way as meta.models.ModelMeta._schema.

In get_schema() you must return the whole schema.org structure.

For a single object it can look like this:

def get_schema(self, context=None):
    return {
        'image': self.object.get_image_full_url(),
        'articleBody': self.object.text,
        'articleSection': self.object.get_categories(),
        'author': self.object.get_schema_author(),
        'copyrightYear': self.object.date_published.year,
        'dateCreated': self.object.get_date(),
        'dateModified': self.object.get_date(),
        'datePublished': self.object.date_published(),
        'headline': self.object.abstract[:50],
        'keywords': self.object.get_keywords(),
        'description': self.object.get_description(),
        'name': self.object.title(),
        'url': self.object.get_full_url(),
        'mainEntityOfPage': self.object.get_full_url(),
        'publisher': self.object.get_site(),
    }

Note

as it’s schema responsibility to convert objects to types suitable for json encoding, you are not required to put only literal values here. Instances of Meta, dates, iterables and dictionaries are allowed.

Meta

The low level interface is meta.views.Meta._schema() attribute or (schema argument to Meta constructor):

class MyView(View):

    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        context['meta'] = Meta(schema={
            '@type': 'Organization',
            'name': 'My Publisher',
            'logo': Meta(schema={
                '@type': 'ImageObject',
                'url': self.get_image_full_url()
            })
        })
        return context