Django - full username as unicode

I have many models associated with User , and I would like my templates to always display its full_name, if available. Is there a way to change the default value of User __unicode__() ? Or is there another way to do this?

I have a profile model registered where I can define __unicode__() , should I link all my models to it? This seems to be not a good idea.


Imagine I need to display a form for this object

 class UserBagde user = model.ForeignKey(User) badge = models.ForeignKey(Bagde) 

I will need to select a field with __unicodes__ for each object, right?
How can I have full names in user?

+6
source share
4 answers

Try the following:

 User.full_name = property(lambda u: u"%s %s" % (u.first_name, u.last_name)) 

EDIT

Apparently what you want already exists ..

https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.get_full_name

also

if you want the unicode function to be replaced:

 def user_new_unicode(self): return self.get_full_name() # Replace the __unicode__ method in the User class with out new implementation User.__unicode__ = user_new_unicode # or maybe even User.__unicode__ = User.get_full_name() 

Return if fields are empty

 def user_new_unicode(self): return self.username if self.get_full_name() == "" else self.get_full_name() # Replace the __unicode__ method in the User class with out new implementation User.__unicode__ = user_new_unicode 
+17
source

If you have a profile model configured as suggested by Django , you can specify the full name on this model

 from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User) ... @property def full_name(self): return "%s %s" % (self.user.first_name, self.user.last_name) 

then anywhere you have access to the user object, which you can easily do user.get_profile.full_name

Alternatively, if you only need the full name in the template, you can write a simple tag:

 @register.simple_tag def fullname(user): return "%s %s" % (user.first_name, user.last_name) 
+2
source

Just hit get_full_name on the __unicode__ method, for example:

 User.__unicode__ = User.get_full_name 

Make sure you redefine it with the called function, not the result of the function. User.get_full_name() will end with open and closing brackets.

Put on any attached file and you should be good.

+1
source

I found there a quick way to do this in Django 1.5. Check this out: user user models

and I also notice

 User.__unicode__ = User.get_full_name() 

what kind of evaluations of Francis Yaconiello do not work on my side (Django 1.3). Error call:

 TypeError: unbound method get_full_name() must be called with User instance as first argument (got nothing instead) 
0
source

Source: https://habr.com/ru/post/922576/


All Articles