R
R
Ruslan Bergutov2015-11-30 07:53:20
Django
Ruslan Bergutov, 2015-11-30 07:53:20

How to get value in class view?

There is such a design, class-based view, how can I get the value of a specific property of my own object?
For example, the value of the property name or last_accessed? Tried get_context_data methods but didn't figure out
models.py

class Author(models.Model):
    salutation = models.CharField(max_length=10)
    name = models.CharField(max_length=200)
    email = models.EmailField()
    last_accessed = models.DateTimeField()

views.py
class AuthorDetail(DetailView):
    model = Author
    template_name = 'author_detail.html'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
marazmiki, 2015-11-30
@Scirocco

Where to get? In the template, in the logic of the view? If inside a view, then in any method, including the notorious get_context_data(), you can access the object by calling the get_object() method:

def get_context_data(self, **kwargs):
    author = self.get_object()
    kwargs.update(last_accessed=author.last_accessed,
                  name=author.name)
    return super().get_context_data(**kwargs)
If we are talking about a template, then by default a variable with an object is called unpretentiously - object. Respectively. in the text of the template, you can write
Hi, {{ object.name }}, you're seen at {{ object.last_accessed }}
If you don't like the object name, you can specify the name of this variable through the context_object_name attribute of your CBV:
class AuthorDetail(DetailView):
    context_object_name = 'author'
    model = Author
    template_name = 'author_detail.html'
and it will be possible to write in the template:
Hi, {{ author.name }}, you're seen at {{ author.last_accessed }}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question