Reputation: 3966
I want to assign a specific field of an object to another context
variable. With function based views, this is simply a matter of declaring the key:value pairs:
context = {
'title': my_object.nick_name
}
Now in my template, I can use the variable {{ title }}
and it'll display the object's field nick_name
.
How would I achieve the same thing with Class Based Views?
For example, I have this simple DetailView:
class MyObjDetail(DetailView):
model = MyObject
def get_context_data(self, **kwargs):
context = super(MyObjectDetail, self).get_context_data(**kwargs)
context['title'] = ????? <--- right here
context['cancel'] = reverse_lazy('my_objs:my_objs_list')
return context
I want to assign the variable {{ title }}
to be the nick_name
field of the object being displayed with this class based view. How would I do that?
Upvotes: 3
Views: 1246
Reputation: 308769
In the DetailView
, you'll be able to access the object with self.object
. Therefore you should do:
context['title'] = self.object.nick_name
However, you might find it easier to simply access the nickname via the object in the template:
{{ object.nickname }}
Upvotes: 5