我有一个 HTML 格式的 Django 模板。我想使用上下文将变量传递给该模板。但是,当我渲染模板时,Django 会使用 TEMPLATE_STRING_IF_INVALID 设置指定的字符串填充引用该变量的空间(我对此进行了测试)。
这是相关的 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),
)
这是它引用的 View :
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))
我相当确定这是由于指定上下文时的语法错误造成的,但在查看了一小时后我找不到它。如果您认为相关,我很乐意发布其他代码。谁能发现我的错误吗?
感兴趣的人的模板:
{% 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>
最佳答案
OP 写道:
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.
关于python - Django 上下文不渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24333618/