Django “xxxxxx Object” display customization in admin action sidebar

前端 未结 9 1036
野的像风
野的像风 2020-12-02 10:07

I would like to change the default behavior of how the admin recent changes sidebar displays the name of \"objects\" added. Refer to the picture below:

相关标签:
9条回答
  • 2020-12-02 10:44

    Using the __str__ method works on Python3 and Django1.8:

    class MyModel(models.Model):
    
        name = models.CharField(max_length=60)
    
        def __str__(self):
            return 'MyModel: {}'.format(self.name)
    
    0 讨论(0)
  • 2020-12-02 10:45

    __unicode__ does do that. Your model should look something like this:

    class SomeModel(models.Model):
        def __unicode__(self):
           return 'Policy: ' + self.name
    

    On Python 3 you need to use __str__:

    def __str__(self):
       return 'Policy: ' + self.name
    
    0 讨论(0)
  • 2020-12-02 10:50

    You're right in thinking that __unicode__ does that. I have this running right now:

    class Film(models.Model):
        title = models.CharField(max_length=200)
        ...
        def __unicode__(self):
            return self.title
    

    When I look in the recent actions list, I see the title of the film that I have just edited.

    0 讨论(0)
  • 2020-12-02 10:50

    Since this question is 6 years old, a lot of things have changed. Let me make an update to it.With python3.6 and the latest version of Django (2.1.2) you should always use __str__() in new code. __unicode__() is an old story for python2.7 because in python3, str is unicode.

    0 讨论(0)
  • 2020-12-02 10:54

    This would work, using def str(self): which returns self.title

    Use something like:

    class Blog(models.Model):
        title = models.CharField(max_length=200)
        def __str__(self):
            return self.title
    
    0 讨论(0)
  • 2020-12-02 10:57

    The answers mentioning __str__ and __unicode__ methods are correct. As stated in the docs however, since version 1.6 (I think), you can use the python_2_unicode_compatible decorator for both Python 2 and Python 3:

    from __future__ import unicode_literals
    from django.utils.encoding import python_2_unicode_compatible
    
    @python_2_unicode_compatible
    class MyClass(models.Model):
        def __str__(self):
            return "Instance of my class"
    

    You can use the above in non-Model objects as well.

    0 讨论(0)
提交回复
热议问题