2

I have many places in my app where user (from user model) is displayed: templates, forms, fliters, tables etc. It is displayed as username everywhere.

I want it to be displayed as first_name/last_name.

I can do that with monkey patching:

@receiver(request_started)
def patch(*args, **kwargs):
    get_user_model().__str__ = my_smart_str_func

I use "request_started" to make sure all models are loaded. (BTW, does there is something like "models loaded" signal?).

How ever, I feel it a little bit hacky. There should be more pythonic way to do that. Am I miss something?

user996142
  • 2,753
  • 3
  • 29
  • 48
  • Have you tried [extending Django's User model](https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-the-existing-user-model), then overriding `__str__()` there? – nofinator Apr 28 '15 at 15:18
  • Well, my change is "purely behavioral", so I need to create proxy, right? But in this case I'll need to use it EVERYWHERE instead of User. And if I create custom class and install it via settings.py it will look strange: why do I need to replace user model just to change its string representation? – user996142 Apr 28 '15 at 15:22
  • 1
    Yes, it is purely behavioral, so you will need to set `proxy = True`. I found some more examples here: http://stackoverflow.com/q/3966483/245915. I can't say for sure until you actually try it, but Django is pretty good about calling unicode() (or str() if you are using Python 3) whenever it is displaying models, whether it's in a form, template, table, etc. So I think extending User and overriding unicode() (Python 2) or str() (Python 3) should cover all those cases. – nofinator Apr 28 '15 at 15:38
  • Not sure what the hell you are doing from your desription, but signals doesn't sound like the correct approach. Personally I would try creating my own user model by extending the user model, and overriding the __unicode__ or __str__ method to dispaly the user name. – wobbily_col Apr 28 '15 at 21:40
  • I do not like idea of extending user model just to change its string representation. And with proxy I will need to use this proxy class instead of my user everywhere. So, I stay with monkeypatching. But signal is not good idea, I will use ``AppConfig.ready()`` instead – user996142 Apr 29 '15 at 12:52

0 Answers0