I have a few models having User as Foreign Key. The User list is displaying the username, but I'd like to customize it. Do I have to extend the User model with a custom model and write my own __str__ function? Is there an easier way?
I don't think you can use a callable for fieldset, right?
I think __unicode__() method is not the correct, you should use __str__() method.
For Python 2.x, __str__() method will return str(bytes) and __unicode__() method will return unicode (text).
The print statement and the str built-in call
__str__()to determine the human-readable representation of an object. The unicode built-in calls__unicode__()if it exists, and otherwise falls back to__str__()and decodes the result with the system encoding. Conversely, the Model base class automatically derives__str__()from__unicode__()by encoding to UTF-8. read here complete
But in Python 3.x there is just __str__(), no __unicode__() method.
Django provides a simple way to define
__str__()and__unicode__()methods that work on Python 2 and 3: you must define a__str__()method returning text and to apply the python_2_unicode_compatible() decorator.On Python 3, the decorator is a no-op. On Python 2, it defines appropriate
__unicode__()and__str__()methods (replacing the original__str__()method in the process).
Here is an example from django docs.
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class MyClass(object):
def __str__(self):
return "Instance of my class"
SOLUTION : Decorate in the same way, as done above for your Class and
in models.py, add a method which will be get added to the User model.
from django.contrib.auth.models import User
def get_name(self):
return '{} {}'.format(self.first_name, self.last_name)
User.add_to_class("__str__", get_name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With