Search code examples
djangodjango-templatesdjango-sekizai

How can I convert a python object to string using the context?


I am trying to render object instances in django templates the way forms do it. So somewhere in a view an object instance gets created: my_object = MyObject() and passed to the template in the context: context['my_object'] = my_object.

When the template is processed, the __str__() method of MyObject is called to create a string to be filled in. For MyObject it looks something like this:

def __str__(self):
    """ Render template """
    return mark_safe(
        render_to_string(self.template, {'options': self.options})
    )

Since the object's template would like to add code to the CSS and JS blocks using sekizai, I need the rendering context. Is there a way (e.g., using an different method) to get this context?


Solution

  • I'm afraid that is not possible and it's not the Django way!

    What I would do is this:

    1. Declare a template (named like mymodel_repr.html).
    2. Write inside it, exactly how I would like to be rendered.
    3. Store it among the other templates (maybe in the app's templates/ folder too).
    4. Change the __str__(self) to return a required field or something else.
    5. Now, each time I want to print an object (in a template way with all the context) of this model, I would simply include it like this: {% include 'mymodel_repr.html' with obj=obj_i_want_to_print %}.

    With this method you are seperating the business from the presentation.

    Hope this helps you!