Raj*_*eev 9 python django django-templates django-models django-views
在Django中,我想在请求中添加一个变量.即
def update_name(request):
names = Employee.objects.filter()
if names.count() > 0:
request.update({"names": name })
return render_to_response('chatlist/newchat.html',
context_instance=RequestContext(request, {'form': form,'msg': msg}))
Run Code Online (Sandbox Code Playgroud)
这是向请求添加变量的正确方法吗?如果没有,我该怎么办?
另外,如何在模板页面中检索相同的值?即
alert ("{{request.names['somename']}}");
Run Code Online (Sandbox Code Playgroud)
你给出的例子是错误的,因为
name未在任何地方分配的变量?无论如何,在python中你可以简单地分配属性,例如
def update_name(request):
names = Employee.objects.filter()
if(names.count() > 0):
request.names = names
return render_to_response('chatlist/newchat.html', context_instance=RequestContext(request,{'form': form,'msg' : msg}))
Run Code Online (Sandbox Code Playgroud)
你甚至不需要分配请求,为什么你不能只将它传递给模板,例如
def update_name(request):
names = Employee.objects.filter()
return render_to_response('chatlist/newchat.html', context_instance=RequestContext(request,{'form': form,'msg' : msg, 'names': names}))
Run Code Online (Sandbox Code Playgroud)
在模板页面中,您可以访问request.name,但如果您只是为了在模板页面中提供变量,那么这不是最好的方法,您可以将上下文字典传递给模板页面.
编辑:另请注意,在模板中使用请求之前,您需要以某种方式传递它,默认情况下它不可用请参阅http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext
| 归档时间: |
|
| 查看次数: |
19788 次 |
| 最近记录: |