Search code examples
djangojoinreversion

Display user name in reference to user id in django template


I expect this is an easy question. For some reason, I don't have a solution yet.

I have an object set from django reversion: version_list. Each object in the set has a user id attached to it. How do I grab the user names that correspond to the user ID's?

To try to be clearer, if each object in version_list has a name, date, and user id, how can I join the version_list set with the user table to figure out what user id goes with which name? This is done in the view, or the template?


Solution

  • I think you're looking for a simple template tag.

    from django import template
    from django.contrib.auth.models import User
    
    register = template.Library()
    
    @register.simple_tag
    def get_username_from_userid(user_id):
        try:
            return User.objects.get(id=user_id).username
        except User.DoesNotExist:
            return 'Unknown'
    

    Which you would use like:

    {% for version in version_list %}
      {% get_username_from_userid version.user_id %}
    {% endfor %}