[英]Django about get_context_data()
I was looking in django source-code to understand super(ExampleView, self).get_context_data(**kwargs)
and why I used it in my view: 我在看Django源代码以了解super(ExampleView, self).get_context_data(**kwargs)
以及为什么在我的视图中使用它:
class ExampleView(TemplateView):
# ... atributes
def get_context_data(self, **kwargs):
context = super(ExampleView, self).get_context_data(**kwargs)
context['key'] = 'value'
return context
I've found: 我发现:
class ContextMixin(object):
"""
A default context mixin that passes the keyword arguments received by
get_context_data as the template context.
"""
def get_context_data(self, **kwargs):
if 'view' not in kwargs:
kwargs['view'] = self
return kwargs
I can't figure it out what that condition or kwargs['view'] = self
does. 我无法弄清楚那个条件或kwargs['view'] = self
是做什么的。
I've tried in my view to overwrite get_context_data()
without that default condition: 我曾尝试在没有该默认条件的情况下覆盖get_context_data()
:
class ExampleView(TemplateView):
# .. atributes
def get_context_data(self, **kwargs):
kwargs['key'] = 'value'
return kwargs
and it worked the same as the first code I've written. 它的工作方式与我编写的第一个代码相同。
Those 2 lines of code add the view as variable to the context if it was not already present. 如果尚不存在,那两行代码会将视图作为变量添加到上下文中。 Most people never use this, but you could do something like this: 大多数人从不使用此功能,但是您可以执行以下操作:
class SomeView(TemplateView):
template_name = "something.html"
title = "My list of books"
def books(self): #custom method
return Book.objects.all()
And then in your template you could reference the books method and title attribute through the view variable: 然后,您可以在模板中通过view变量引用books方法和title属性:
<h1>{{ view.title }}</h1>
<ul>
{% for book in view.books %}
<li>{{ book }}</li>
{% enfor %}
<ul>
Ah yes, and note that you don't even need a custom get_context_data() method in this case 是的,请注意,在这种情况下,您甚至不需要自定义的get_context_data()方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.