A
A
Alexander Vinogradov2017-02-14 22:39:46
Django
Alexander Vinogradov, 2017-02-14 22:39:46

How to work with model object in template?

In models.py I have an Images model.
In the view, I import this model and pass it through the images variable to the template

from app_main.models import Catalogue, FurnitureProduct, Images
.....
def catalog_view(request, catalog_id):
    ......
    images = Images
    contex_var = {.... 'images': images}
    return render(request, template_name, contex_var)

In the template, I'm trying to get data in the same way as it would be received in a python function, i.e. images.objects.get(pk=5).imagepath, but the parser throws an error.
How to work with such an object in a template?
Or more simply, how to pull data from this table?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stepan Krapivin, 2017-02-14
@xevin

If you are trying to fetch data from the database in a template, this is the first sign that you are doing it wrong. MVC separates data, logic, and presentation for a reason.
What is the specific task?

P
Peter, 2017-02-14
@petermzg

A template in order to simply substitute data into it, all logic must be at the controller level.
In the controller, get all the data you need and then pass it to the template.

A
Alexander Vinogradov, 2017-02-15
@ruchej

Thank you all!
Good advice was to prepare the data in the model method.
Added a method to models.py of the FurnitureProduct model

def get_images_path(self):
        im_path = []
        imobj = Images.objects.filter(furnproduct_id=self.pk)
        if imobj:
            for obj in imobj:
                im_path.append(obj.imagepath.url)
        return im_path

And in the template I get a list of values ​​using the method: {{ product.get_images_path }}
I'm a beginner, it never occurred to me.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question