Skip to main content
 首页 » 编程设计

python之Django :UnicodeDecodeError: '

2024年10月24日35exmyth

我想用 Python 2.7 和 Django 1.7.8 构建一个博客。

当我使用 Django 时,我不断收到错误:UnicodeDecodeError。 相关代码为:

#coding: utf-8 
from django.db import models 
class Entry(models.Model): 
    title = models.CharField(max_length=200) 
    body = models.TextField() 
    publish = models.BooleanField(default=False) 

并且./manage.py makemigrations得到一个错误:

    Migrations for 'blog': 
  0001_initial.py: 
    - Create model Entry 
Traceback (most recent call last): 
  File "manage.py", line 10, in <module> 
    execute_from_command_line(sys.argv) 
  File "/usr/local/lib/python2.7/dist-packages/Django-1.7.8-py2.7.egg/django/core/management/__init__.py", line 385, in execute_from_command_line 
    utility.execute() 
  File "/usr/local/lib/python2.7/dist-packages/Django-1.7.8-py2.7.egg/django/core/management/__init__.py", line 377, in execute 
    self.fetch_command(subcommand).run_from_argv(self.argv) 
  File "/usr/local/lib/python2.7/dist-packages/Django-1.7.8-py2.7.egg/django/core/management/base.py", line 288, in run_from_argv 
    self.execute(*args, **options.__dict__) 
  File "/usr/local/lib/python2.7/dist-packages/Django-1.7.8-py2.7.egg/django/core/management/base.py", line 338, in execute 
    output = self.handle(*args, **options) 
  File "/usr/local/lib/python2.7/dist-packages/Django-1.7.8-py2.7.egg/django/core/management/commands/makemigrations.py", line 124, in handle 
    self.write_migration_files(changes) 
  File "/usr/local/lib/python2.7/dist-packages/Django-1.7.8-py2.7.egg/django/core/management/commands/makemigrations.py", line 143, in write_migration_files 
    migrations_directory = os.path.dirname(writer.path) 
  File "/usr/local/lib/python2.7/dist-packages/Django-1.7.8-py2.7.egg/django/db/migrations/writer.py", line 222, in path 
    return os.path.join(basedir, self.filename) 
  File "/usr/lib/python2.7/posixpath.py", line 80, in join 
    path += '/' + b 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 10: ordinal not in range(128) 

我不知道出了什么问题,知道吗?我已经在代码顶部添加了 coding:utf-8

请您参考如下方法:

您的模型中是否已有数据? 如果是这样,我猜你那里有一些坏角色。 您是否在模型上定义了 unicode 或 str 方法? 如果是这样,我建议在类似这样的 try 语句中使用它们:

def __str__(): 
    try: 
       return "%s" % self.title 
    except: 
       return "%s" % self.pk 

当你只看到 PK 时,你就会知道你的'标题'字段有错误数据。 扩展它以包括您想要显示的任何字段,而不仅仅是标题。