在基于类的视图中获取对象属性

时间:2016-01-30 22:45:04

标签: python django django-class-based-views

我想知道是否有可能在Django基于类的视图中获取对象的属性。

我尝试做的是以下内容:

我有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

我知道还有很多其他方法可以实现这一点,但在视图中设置变量非常方便(到目前为止)......

2 个答案:

答案 0 :(得分:1)

没有。你不能定义那样的属性。

您最接近的方法是定义一个返回page_title的{​​{1}}方法,但我不知道如何覆盖self.object.your_field并添加它在那里。

答案 1 :(得分:1)

你可以使用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,感觉有点hacky,但更接近你想要的。我还没有对它进行测试,但我认为它应该可行。

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'