在基于 class 的视图中获取对象属性
Get object attribute in class based view
我想知道是否可以在 Django Class 基于视图中获取对象的属性。
我尝试做的是:
我有一个 UpdateView
:
class FooUpdate(UpdateView):
model = Foo
page_title = <foo-object's name should go here>
page_title
由模板处理
...
<title>
{{ view.page_title }}
</title>
...
(描述了此技术 here)
urls.py
看起来像这样:
...
url(r'^edit/(?P<pk>[0-9]+)/$', views.FooUpdate.as_view(), name="edit")
...
如何在视图中设置 page_title
?
我知道还有很多其他方法可以实现这一点,但是在视图中设置变量真的很方便(到目前为止)...
没有。你不能这样定义属性。
您最接近的做法是定义一个返回 self.object.your_field
的 page_title
方法,但我看不出这比覆盖 get_context_data
并添加更好它在那里。
您可以使用 mixin 来实现类似的效果。
class ContextMixin:
extra_context = {}
def get_context_data(self, **kwargs):
context = super(ContextMixin, self).get_context_data(**kwargs)
context.update(self.extra_context)
return context
class FooUpdate(ContextMixin, UpdateView):
model = Foo
extra_context={'page_title': 'foo-objects name should go here'}
编辑:一个不同的 mixin,感觉有点老套,但更接近你想要的。我还没有测试过,但我认为它应该可以工作。
class AutoContextMixin:
def get_context_data(self, **kwargs):
context = super(AutoContextMixin, self).get_context_data(**kwargs)
for key in dir(self):
value = getattr(self, key)
if isinstance(value, str) and not key.startswith('_'):
context[key] = value
return context
class FooUpdate(AutoContextMixin, UpdateView):
model = Foo
page_title = 'foo-objects name should go here'
我想知道是否可以在 Django Class 基于视图中获取对象的属性。
我尝试做的是:
我有一个 UpdateView
:
class FooUpdate(UpdateView):
model = Foo
page_title = <foo-object's name should go here>
page_title
由模板处理
...
<title>
{{ view.page_title }}
</title>
...
(描述了此技术 here)
urls.py
看起来像这样:
...
url(r'^edit/(?P<pk>[0-9]+)/$', views.FooUpdate.as_view(), name="edit")
...
如何在视图中设置 page_title
?
我知道还有很多其他方法可以实现这一点,但是在视图中设置变量真的很方便(到目前为止)...
没有。你不能这样定义属性。
您最接近的做法是定义一个返回 self.object.your_field
的 page_title
方法,但我看不出这比覆盖 get_context_data
并添加更好它在那里。
您可以使用 mixin 来实现类似的效果。
class ContextMixin:
extra_context = {}
def get_context_data(self, **kwargs):
context = super(ContextMixin, self).get_context_data(**kwargs)
context.update(self.extra_context)
return context
class FooUpdate(ContextMixin, UpdateView):
model = Foo
extra_context={'page_title': 'foo-objects name should go here'}
编辑:一个不同的 mixin,感觉有点老套,但更接近你想要的。我还没有测试过,但我认为它应该可以工作。
class AutoContextMixin:
def get_context_data(self, **kwargs):
context = super(AutoContextMixin, self).get_context_data(**kwargs)
for key in dir(self):
value = getattr(self, key)
if isinstance(value, str) and not key.startswith('_'):
context[key] = value
return context
class FooUpdate(AutoContextMixin, UpdateView):
model = Foo
page_title = 'foo-objects name should go here'