在django、python中,上下文和上下文之间有什么区别?
我总是在我的方法中使用上下文,直到我遇到这个观点:在django、python中,上下文和上下文之间有什么区别?,python,django,Python,Django,我总是在我的方法中使用上下文,直到我遇到这个观点: def index(request): context = RequestContext(request) top_category_list = Category.objects.order_by('-likes')[:5] for category in top_category_list: category.url = encode_url(category.name) context
def index(request):
context = RequestContext(request)
top_category_list = Category.objects.order_by('-likes')[:5]
for category in top_category_list:
category.url = encode_url(category.name)
context_dict = {'categories': top_category_list}
cat_list = get_category_list()
context_dict['cat_list'] = cat_list
page_list = Page.objects.order_by('-views')[:5]
context_dict['pages'] = page_list
if request.session.get('last_visit'):
# The session has a value for the last visit
last_visit_time = request.session.get('last_visit')
visits = request.session.get('visits', 0)
if (datetime.now() - datetime.strptime(last_visit_time[:-7], "%Y-%m-%d %H:%M:%S")).days > 0:
request.session['visits'] = visits + 1
else:
# The get returns None, and the session does not have a value for the last visit.
request.session['last_visit'] = str(datetime.now())
request.session['visits'] = 1
# Render and return the rendered response back to the user.
return render_to_response('rango/index.html', context_dict, context)
在上面的函数中有context_dict和context?为什么呢
以下两者之间是否也有区别:
context_dict={'categories':top_categories_list}
和
上下文目录['categories']=顶级目录列表
还是这完全一样
谢谢你们 这几乎是完全相同的,第一个是定义新字典并在其中放入新的键/值,而第二个只是在其中放入新的键:值,因为已经定义了dic 在现代的django,你可以
return render(request, 'index.html', context_dic)
其中render已为您处理RequestContext。这样可以避免一些混淆
是一本简单的字典context\u dict
是一个实例或请求上下文context
render_to_response()
context_dict
被(临时)添加到context
实例中
代码(在这种情况下)可以写得更清楚(IMHO),如下所示:
如果django>=1.3,可以使用
return render(request, 'rango/index.html', context_dict)
关于你的另一个问题
context_dict={'categories':top_categories_list}
create e new dict
context\u dict['categories']=top\u categories\u list
将一个新条目分配(或添加)到现有的词典中实际上,在Django 1.11中,这个小改动似乎起到了作用
定义dict:(不需要上下文,仅定义dict)
然后,更改行以获取命令:
返回render\u to\u响应('rango/index.html',context\u dict)
这对于模板视图更有意义,您可以读取请求并返回带有(结果)上下文的响应
注意:当需要从标题(请求)中获取额外信息时,这可能不起作用。这段代码是否正常工作?这段代码来自下面的教程,尽管我的索引视图与那个略有不同,因为这段代码完全把我与这些上下文和上下文混淆了,所以我不确定这段代码是否正确,谢谢你的解释!虽然我还是很困惑。。为什么我们不能只使用一个上下文?在render_to_响应中,我们使用上下文和上下文,而在render_to_响应中,我们只使用一个上下文?这是否正确?@Anita no,在
render
中,您不需要使用context
,您只需要模板context,在本例中是context\u dict
return render(request, 'rango/index.html', context_dict)