[Answer]-Django – getting the requested user object in the template through models method

1👍

There is no RequestContext object available in the get_rendered_html() method so you can’t pass it as a context_instance argument of the render_to_string(). This is why the user variable is not available in the template.

You should pass the User instance to get_rendered_html() method and propagate it to the template:

def get_rendered_html(self, user=None):
    template_name = '%s_activity.html' %(self.content_type.name)
    return render_to_string(template_name, {
        'object':self.content_object,
        'actor':self.actor,
        'action':self.action,
        'user':user,
    })

If you want to call this method from other template then the best option is to use custom template tag:

# app/templatetags/activity_tags.py
# and don't forget to create empty app/templatetags/__init__.py :-)
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.simple_tag(takes_context=True)
def render_activity(context, activity):
    user = context['user']
    html = activity.get_rendered_html(user)
    return mark_safe(html)

And then load and use this tag library in your template:

{% load activity_tags %}
...
{% render_activity activity %}

Leave a comment