2

I want the events.html template to format the string somehow, but I do not know how I would do that. The way I have it below is how I would think it should work, but it doesn't.

events.html

{% extends "base.html" %}
{% block content %}
{% for object in objects %}
<h1>{{object.name}}</h1>
<p>When: {{ "It will take place in the year %s and the month %s" % (object.when.year, object.when.month) }}</p>
{% endfor %}
{% endblock %}

views.py

from django.template.response import TemplateResponse
import pdb
from events.models import Event

def home(request):
    objects = Event.objects.all()
    return TemplateResponse(request, 'events.html', {'objects': objects}); 
2
  • Does it throw an error? If not, what is the output? And are object.when.year and object.where.month both integers? Commented Jan 5, 2014 at 7:54
  • "Could not parse the remainder" I'm assuming it's treating the "%" as a modulo operator Commented Jan 5, 2014 at 7:56

1 Answer 1

2

Why interpolate when you don't need to? Try the following:

<p>When: It will take place in the year {{ object.when.year }} and the month {{ object.when.month }}</p>

Another thought: regarding your string interpolation, the docs say the following:

For this reason, you should use named-string interpolation (e.g., %(day)s) instead of positional interpolation (e.g., %s or %d) whenever you have more than a single parameter. If you used positional interpolation, translations wouldn’t be able to reorder placeholder text.

So, first off, you need to enclose the arguments to be interpolated as a dict, which dictates that they're enclosed in curly brackets, not parentheses as you have in your code. Then, you should use named parameters, rather than relying on positional interpolation.

{{ "It will take place in the year %(year) and the month %(month)." % {'year': objects.when.year, 'month': objects.when.month} }}
Sign up to request clarification or add additional context in comments.

2 Comments

Well, I guess for this example I didn't really need to, but I thought it would be useful to know how to. But I didn't really think of doing it the basic way, I guess I'm tired..
Fair enough. In addition to my initial suggestion, I've provided an explanation for what went wrong in your original code. If it helps, please consider accepting this answer as correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.