2

I am new to Django and I am trying to find out how can I associate a HTML snippet with a model.

My HTML snippet is just a div. I want to reuse that div (you can think of it like a thumbnail)

Situation is like this: In my main page I want to show x objects and in my search page I want to show more objects. But the representation is the same.

I can write in the mainpage.html and searchpage.html the desired way of transforming the model object into a div but I am not sure what is the best way to reuse that transform?

I can add a function to my model which returns a HTML div, then I can call it from mainpage and searchpage templates. But that will couple the model and representation, which I believe is not a very nice thing to do.

If I am not mistaken inclusion_tags are the way to go but in which file should I keep the function definition?

1 Answer 1

3

As you rightly say, you don't want html in your models, it's goes against the MVC pattern.

Models are for storing data. Views are for selecting the data to present whilst Templates are used for the actual presentation of data. (See this note on django's interpretation of MVC).

To answer your question, you need a template (or even a template tag), to represent your model, say model_block.html. Something like

{% if obj %}
    <div id=obj.id>
        {{ obj.name }}
    </div>
{% endif %}

Then include your template in your mainpage.html like

{% for obj in object_list %}
    {% include 'model_block.html' %}
{% endfor %}

You can do the same thing in your searchpage.html, passing a different object_list variable from your view.

Sign up to request clarification or add additional context in comments.

Comments

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.