在django中添加一个变量来请求
在 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}))
这是向请求添加变量的正确方法吗?如果不是,我该怎么办?
另外,如何在模板页面中检索相同的值? IE,
alert ("{{request.names['somename']}}");
In Django I want to add a variable to the request. i.e,
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}))
Is this the right way to add a variable to the request? If not, how should I do it?
Also, how can I retrieve the same value in the templates page? i.e,
alert ("{{request.names['somename']}}");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您给出的示例是错误的,因为
name
变量?无论如何,在Python中你可以简单地分配属性,例如
你甚至不需要分配给请求,为什么你不能将它传递给模板例如
并且在模板页面中你可以访问request.name,尽管如果你是这样做只是为了在模板页面中提供一个可用的变量,这不是最好的方法,您可以将上下文字典传递给模板页面。
编辑:另请注意,在模板中使用请求之前,您需要以某种方式传递它,默认情况下它不可用,请参阅 http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext
The example you have given is wrong because
name
variable which you haven't assigned anywhere?Anyway, in python you can simply assign attributes, e.g.
Also you don't even need to assign to request, why can't you just pass it to template e.g.
And in the template page you can access request.name, though if you are doing this just to have a variable available in template page, it is not the best way, you can pass context dict to a template page.
Edit: Also note that before using request in template you need to pass it somehow, it is not available by default see http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext
工作代码!!
假设有一个名为 my_name 的变量。我会将其添加到 get 和 post 请求中。
在 Get 请求中添加变量
在 POST 请求中添加变量
现在,在请求中添加了一个名为 my_name 的变量。
要获取其值,请使用以下代码 -
输出:Nidhi
Working Code !!
Assume a variable named my_name. I will add this to get and post requests.
To add variable in Get request
To add variable in POST request
Now here in request there is a variable added name my_name.
To get its value use below code -
Output : Nidhi