【问题标题】:Django error with TypeError: must be unicode not str带有 TypeError 的 Django 错误:必须是 unicode 而不是 str
【发布时间】:2014-11-22 10:33:10
【问题描述】:

将我的 django 项目迁移到 heroku 时遇到了一些问题。执行 heroku run python manage.py syncdb 然后输入超级用户和密码时出现以下错误。

 File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/text.py", line 409, in slugify
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
TypeError: must be unicode, not str

我的模型.py

from django.db import models
from django.db.models.signals import post_save
from django.conf import settings
from django.contrib.auth.models import User
from autoslug import AutoSlugField


# Create your models here.
class Profile(models.Model):
    account = models.OneToOneField(User, unique=True)
    name = models.CharField(max_length = 120, null=True, blank=True)
    location = models.CharField(max_length = 120, null=True, blank=True)
    website = models.CharField(max_length = 120, null=True, blank=True)
    bio = models.CharField(max_length = 120, null=True, blank=True)
    timestamp = models.DateTimeField(auto_now = False, auto_now_add=True)
    updated_timestamp = models.DateTimeField(auto_now = True, auto_now_add=False)
    slug = AutoSlugField(populate_from="account")

    @models.permalink
    def get_absolute_url(self):
        return ('view_profile', None, {'username': self.account.username})

    def __unicode__(self):
        return str(self.account.username)

# here is the profile model
def user_post_save(sender, instance, created, **kwargs):
    """Create a user profile when a new user account is created"""
    if created == True:
        p = Profile()
        p.account = instance
        p.save()

post_save.connect(user_post_save, sender=User)

【问题讨论】:

    标签: python django signals slug


    【解决方案1】:

    您正在尝试在关系字段上使用AutoSlugField。您只能在返回文本的属性上使用AutoSlugField,而不是另一个模型实例。创建一个属性,该属性返回您对用户的哪个元素进行 slugify:

    class Profile(models.Model):
        slug = AutoSlugField(populate_from="_accountname")
        # [....]
    
        @property
        def _accountname(self):
            return self.account.username
    

    另外说明:您的 __unicode__ 方法必须返回 unicode 对象,但您的方法返回 str 对象:

    def __unicode__(self):
        return str(self.account.username)
    

    删除str() 调用:

    def __unicode__(self):
        return self.account.username
    

    【讨论】:

      【解决方案2】:

      尝试将 Profile 模型上的 unicode 函数更改为以下内容:

      def __unicode__(self):
          return u'%s' % self.account.username
      

      【讨论】:

      • self.account.username 已经是一个 unicode 值。如果不是,您可以使用unicode(self.account.username)
      • 我试过了,没用。我会试试@MartijnPieters 的答案
      • @cloudviz:你没有包括你的整个追溯,所以我不得不做一些猜测;皮埃尔也做了,但没有猜对。经验教训:下次包括整个回溯。
      猜你喜欢
      • 2016-11-18
      • 2019-03-15
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多