DEV Community

loading...
Cover image for Use Django to Add Schema for Rich Results

Use Django to Add Schema for Rich Results

qosha1 profile image Quinn ・2 min read

I recently went through the process of learning about Schema markup and how to use it and figured I would share what I ended up with.

For my website, I built a feature where users can search for different car shows that are going on in their area but I wanted the results to be able to show up similar to how they do on Eventbrite and the other larger sites so I started to investigate Schema. Generally, it's pretty self explanatory once you go through a few of the examples at their docs page:

https://schema.org/Event

However, I was using Django and wanted to make sure that the results could be looped through using the Django template engine. For instance, for car shows in houston I just set the Event markup to loop through the queryset and use the appropriate data pieces. Of course, you'll need to put in you specific model attributes. See the full example of what I used below. Just add this code to the rest of your scripts and you'll be off to the races.

You'll also likely want to add the single event markup to the detail page of your events.

While generally pretty straightforward, the json code is very particular about ending commas so you have to make sure the last one isn't there with an if statement. Google search console will also still suggest that you add a few additional parameters if you use the rich text results tool that they provide. These aren't dealbreakers though so you can choose to implement or not.

Hope this helps on your journey to improve your site with Rich Results!

<script type="application/ld+json">
[
{% for event in events %}
{
"@context": "https://schema.org",
"@type": "Event",
"name": "{{ event.title }}",
"description": "{{ event.description }}",
"image": "{{ event.logo.url }}",
"location": {
"@type": "Place",
"address": {
"@type": "PostalAddress",
"addressLocality": "{{ event.locality.name }}",
"addressRegion": "{{ event.state.code }}",
"postalCode": "{{ event.postal_code }}",
"streetAddress": "{{ event.street_address }}"
},
"geo":{
"@type":"GeoCoordinates",
"latitude":"{{ event.location.latitude }}",
"longitude":"{{ event.location.longitude }}"
}
},
"startDate": "{{ event.start_time|date:'c' }}",
"endDate": "{{ event.end_time|date:'Y-m-d' }}T{{ event.end_time|time:'H:i' }}",
"url": "{{ event.get_absolute_url }}"
}{% if not forloop.last %},{% endif %}
{% endfor %}
]
</script>

Discussion

pic
Editor guide