Python 2.7__unicode__(self) not working

2020-07-18 06:42发布

unicode(self) is not working for me. I can still see 'Name Object' in the admin. My code is as follows:

import datetime # standard python datetime module
from django.db import models # Djangos time-zone-related utilities
from django.utils import timezone

class Name(models.Model):
    name = models.CharField(max_length=200)

def __unicode__(self):  # Python 3: def __str__(self):
    return self.name

Thanking you

标签: python django
2条回答
forever°为你锁心
2楼-- · 2020-07-18 07:19

The problem you have is that you need to define the __unicode__ method within the class definition.

import datetime # standard python datetime module
from django.db import models # Djangos time-zone-related utilities
from django.utils import timezone

class Name(models.Model):
    name = models.CharField(max_length=200)

    def __unicode__(self):  # Python 3: def __str__(self):
        return str(self.name)

should work for you.

查看更多
欢心
3楼-- · 2020-07-18 07:27

Python INDENTION will be responsible most of the time, to work correclty, use the editor or separate out the _unicode_(self) with tab

      def __unicode__(self):  # Python 3: def __str__(self):
            return str(self.name)
查看更多
登录 后发表回答