将django startapp命令与自定义应用模板一起使用时,我收到一个奇怪的错误。我创建了一个自定义应用程序模板,我有一个文件models.py
,其中包含unicode字符:
# -*- coding: utf-8 -*-
from django.db import models
class {{app_name|capfirst}}(models.Model):
"""Toto je text dokumentace. Žluťoučký kůň"""
pass
当我运行python manage.py startapp --template=core/my_app_template application
时,models.py
文件无法获取并且我收到此错误:
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 459, in execute_manager
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/startapp.py", line 25, in handle
super(Command, self).handle('app', app_name, target, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/templates.py", line 162, in handle
new_file.write(content)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u017d' in position 112: ordinal not in range(128)
如何对文件进行编码以便进行处理?我认为# -*- coding: utf-8 -*-
已经足够了。或者我应该在settings.py
?
我查看了代码,并在将内容写入文件时抛出了错误:
with open(new_path, 'w') as new_file:
new_file.write(content)
所以我怀疑这是django的错。
答案 0 :(得分:1)
with open(new_path, 'w') as new_file:
new_file.write(content).encode('utf-8')
答案 1 :(得分:0)
我使用了Django 1.4。 Django 1.5解决了这个问题。他们更新了代码并完全按照凯瑟琳的建议。