问题描述
是否可以将某些参数从动态 urls
(我有 ^ c/(?P< username> \ w +)/^
)传递给自定义context_processors
?
Is it possible to pass some argument from dynamic urls
(I have ^c/(?P<username>\w+)/^
) to custom context_processors
?
views.py(我将 username
从url传递给 RequestContext
)
views.py (I pass username
from url to RequestContext
)
def client_profile(request, username):
# .... some context
return render_to_response('profile.html', context,
context_instance=RequestContext(request, username))
context_processors.py
context_processors.py
def default_profile(request, username):
client = get_object_or_404(Client, user__username=username)
#.... some default
return {
'client': client,
#.... some default
}
我尝试了这个,但是当我重新加载页面时却出错了
I try this, but it was an error when I reload a page
还有其他方法可以做这样的事情吗?还是真的不可能?
Is any another way to do something like this? Or is it really not possible?
-谢谢.
推荐答案
上下文处理器非常简单,只有一个参数. HttpRequest
Context processors are fairly simple, with only 1 argument; HttpRequest
您可以做的是在会话中添加一些内容,因为可以通过请求进行访问,但是除非是系统范围的内容或相当通用的内容,否则通常最好通过视图提供上下文变量.具体来说,在您的示例中,如果要在URL中提供用户名,那么您将在该视图的响应中提供上下文,因此您只需在此时提供 client
.
What you could do, is add something to the session because that would be accessible via the request, but unless it's something system wide or quite generic then you are often better off providing your context variables via your views. Specifically in your example, if you're providing a username in an URL, you are providing a context in the response of that view, so you could simply provide the client
at that point.
无论如何,如果您在会话中提供了一些东西,您的代码可能看起来像这样;
Anyway, if you provided something through the session your code might look like;
def client_profile(request, username):
# .... some context
request.session['username'] = username
return render_to_response(
'profile.html', context,
context_instance=RequestContext(request, username)
)
def default_profile(request):
context = {}
if 'username' in request.session:
username = request.session['username']
client = get_object_or_404(Client, user__username=username)
context.update({
'client': client,
})
return context
这篇关于如何在自定义context_processors.py上传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!