Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change User representation in Django Admin when used as Foreign Key?

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?

like image 928
vicusbass Avatar asked Jun 28 '16 21:06

vicusbass


1 Answers

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)
like image 198
Surajano Avatar answered Sep 30 '22 13:09

Surajano