0

I have a simple model like this

class UserType( models.Model ) :
    def __unicode__( self ) :
        return self.name

    TYPE_CHOICES = (
        ( 'ad', 'administrator'    ),
        ( 'mo', 'moderator'        ),
        ( 'vi', 'viewer'           ),
        ( 'pm', 'property manager' ),
        ( 'po', 'property owner'   ),
        ( 'vm', 'vendor manager'   ),
        ( 've', 'vendor'           ),
        ( 'te', 'tenant'           ),
    )

    name = models.CharField( max_length = 2, choices = TYPE_CHOICES )

In the admins.py, I set filter_horizontal = ( 'user_types', ) for UserProfile, which has a ManyToManyField to UserType. But in the UserProfile admin page, the horizontal filter for M2M only shows the short-name of the tuple:

Also in a template, I want to show a list of user types a particular user has. So my template code looks like this

User type:
<ul>
    {% if user_object.profile.user_types.all %}
        {% for user_type in user_object.profile.user_types.all %}
            <li>{{ user_type|capfirst }}</li>
        {% endfor %}
    {% else %}
        <li>No user type</li>
    {% endif %}
</ul>

And on the template, it displays only the short-name. I know normally I could show it the long-name by doing something like {{ get_user_type_display }}, but in this case for M2M, it doesn't work.

So my question is two-fold:

  1. How do I display the long-name of a M2M choice/tuple in the admin page?
  2. How do I display the long-name in a M2M choice/tuple in a template?
hobbes3
  • 28,078
  • 24
  • 87
  • 116
  • possible duplicate of [Django: Display Choice Value](http://stackoverflow.com/questions/4320679/django-display-choice-value) – Burhan Khalid Apr 09 '12 at 07:26
  • That won't work on line 5 of the template code. `
  • {{ get_user_type_display|capfirst }}
  • ` will result in an invalid template variable. I can tell because I set `TEMPLATE_STRING_IF_INVALID` in `settings.py`. Also what about my first question? I may be wrong, but I think you probably thought "TL;DR" and only read the last part of my question. I already stated that I know about `get_FOO_display`. – hobbes3 Apr 09 '12 at 07:35
  • You are right, because you need to use `user_type_name_display` `FOO` is the name of field you want the display for. – Burhan Khalid Apr 09 '12 at 07:42
  • Thanks for the suggestion. I finally got it working with `user_type.get_name_display` :-). Any clue about the admin page? – hobbes3 Apr 09 '12 at 07:58