Django rest framework 返回错误信息 __str__ returned non-string (type NoneType)

Django rest framework 返回错误信息 __str__ returned non-string (type NoneType)

Django rest framework 返回错误信息 str returned non-string (type NoneType)

错误信息如下: 
这里写图片描述

这里写图片描述

此时点击右上角的admin,把帐号退掉,然后在进入对应页面就可以了

这里写图片描述

如果不退出admin账号的话,我们看到在自己写的users模型中 替换了django自带的AbstractUser

然后又设置了name可以为空,所以返回non-string

修改方法:

str的函数中,将返回值设置成AbstractUser里面的username就好了

apps.users.models源码:

from django.contrib.auth.models import AbstractUser



class UserProfile(AbstractUser):
    """
    用户
    """
    # CharField 一定要加max_length参数,说明这个字段的最大长度
    name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名")
    birthday = models.DateField(null=True, blank=True, verbose_name="出生年月")
    gender = models.CharField(max_length=6, choices=(("male", u"男"),("female", u"女")),default="female", verbose_name="性别")
    mobile = models.CharField(max_length=11, verbose_name="电话")
    email = models.EmailField(max_length=100, null=True, blank=True, verbose_name="邮箱")

    class Mate:
        verbose_name = "用户"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

django.contrib.auth.models.AbstractUser源码:

class AbstractUser(AbstractBaseUser, PermissionsMixin):
    """
    An abstract base class implementing a fully featured User model with
    admin-compliant permissions.

    Username and password are required. Other fields are optional.
    """
    username_validator = UnicodeUsernameValidator() if six.PY3 else ASCIIUsernameValidator()

username = models.CharField(
    _('username'),
    max_length=150,
    unique=True,
    help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
    validators=[username_validator],
    error_messages={
        'unique': _("A user with that username already exists."),
    },
)
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页