0

I wonder if it is possible to get the attribute of an object in Django Class Based Views.

What I try to do is the following:

I have an UpdateView:

class FooUpdate(UpdateView):
model = Foo

page_title = <foo-object's name should go here>

page_title is processed by the template with

...
<title>
    {{ view.page_title }}
</title>
...

(this technique is described here)

urls.py looks like this:

...
url(r'^edit/(?P<pk>[0-9]+)/$', views.FooUpdate.as_view(), name="edit")
...

How can I set page_title in the view?

I am aware that there are plenty other ways to achieve this, but setting a variable in the view was really convenient (up to now) ...

2 Answers 2

1

You could use a mixin to achieve something similar.

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'}

Edit: a different mixin, which feels bit hacky, but closer to what you want. I haven't tested it, but I think it should work.

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'
Sign up to request clarification or add additional context in comments.

3 Comments

thank you! but how would I need a mixin for that? The same could be done in FooUpdate itself, or not?
Yes, but with a mixin you can import and reuse the code in multiple classes and apps. So you don't have to write the get_context_data every time, when you only want to add some simple values.
I've added a second mixin example which might be closer to what you are after.
1

No. You can't define attributes like that.

The nearest you could do would be to define a page_title method that returned self.object.your_field, but I don't see how that would be any better than overriding get_context_data and adding it there.

1 Comment

I would still have to adapt the template, right? In this case there is no advantage...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.