2

I've got a Django template in HTML. I would like to pass a variable to this template using a context. However, when I render the template Django fills the spaces that reference this variable with the string specified by the TEMPLATE_STRING_IF_INVALID setting (I tested this).

Here's the relevant URLconf:

from django.conf.urls import patterns, url

from users import views

urlpatterns = patterns('',
    url(r'^$', views.users),
    url(r'(?P<pk>\d+)/$', views.userdetail),
)

and here's the view it references:

from django.template import RequestContext, loader
...
def userdetail(request, pk):
    user = get_object_or_404(User, pk=pk)
    template = loader.get_template('users/userdetail.html')
    context = RequestContext(request, {'user': user})
    return HttpResponse(template.render(context))

I'm fairly certain it's due to a syntax error in specifying the context but after looking at it for an hour I can't find one. I'm happy to post additional code if you think it may be relevant. Can anyone spot my mistake?

Template for those interested:

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif%}

<h1> You are viewing the page for the individual user {{ user.name }} </h1>

    This user has created the following posts:

    {% for post in user.post_list %}
        <a href="/posts/{{ post.id }}/">{{ post.title }}</a></li>
    {% endfor %}

<p>
Created on {{ user.creation_date }}
</p>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Forkstealer
  • 21
  • 1
  • 4
  • I dont think you are rendering the right `context`. It should be `from django.template import Context` – karthikr Jun 20 '14 at 18:42
  • When I saw the comment about the leading ^ I felt like an idiot. I added it and it still doesn't render correctly (exact same issue). I don't know if that makes me feel more or less dumb, but thank you for your input. – Forkstealer Jun 20 '14 at 18:49
  • can you show us your template too? – yedpodtrzitko Jun 20 '14 at 18:53

1 Answers1

2

The OP wrote:

My supervisor just came around and fixed it really quickly. The issue is that templates have some predefined keywords. User is one of these keywords so django was upset that I was passing it {'user':user} in the context. Changing to {'customuser':user} avoids the collision with the django keyword and fixes this issue.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • ([answered in an edit and converted to a community wiki](http://meta.stackoverflow.com/questions/267434/what-is-the-appropriate-action-when-the-answer-to-a-question-is-added-to-the-que).) – Brian Tompsett - 汤莱恩 Jun 06 '15 at 17:29