2013-02-28 80 views
0

當使用django startapp命令與自定義應用程序模板時,我收到了一個奇怪的錯誤。我創建了一個自定義應用程序模板,在那裏我有一個文件models.py Unicode字符是這樣的:與自定義模板的Django startapp unicodeerror

# -*- 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 applicationmodels.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

如果你使用'# - * - coding:utf-8 - * - ',那麼你應該保存UTF-8編碼的文件。 – Matthias 2013-02-28 15:10:07

+0

@Matthias它以UTF-8編碼保存。 – davekr 2013-02-28 15:22:33

回答

0

我用Django 1.4。這個問題用Django 1.5解決了。他們更新了代碼,完全符合凱瑟琳的建議。

1
with open(new_path, 'w') as new_file: 
    new_file.write(content).encode('utf-8') 
+0

這很好,但我認爲如果不分叉django或繼承TemplateCommand類並創建自定義命令,我就無法做到這一點。 – davekr 2013-02-28 15:17:17

+0

我試圖去分岔它。它輸出'AttributeError:'NoneType'對象沒有'編碼'屬性 – davekr 2013-02-28 15:28:46

+0

嘗試new_file.write(content.encode('utf-8')) – catherine 2013-02-28 15:31:23