davekr
davekr

Reputation: 2276

Django startapp with custom template unicodeerror

I am getting a strange error when using django startapp command with custom app template. I created a custom app template and there I have a file models.py with unicode characters like this:

# -*- coding: utf-8 -*-
from django.db import models
class {{app_name|capfirst}}(models.Model):
    """Toto je text dokumentace. Žluťoučký kůň"""
    pass

When I run python manage.py startapp --template=core/my_app_template application the models.py file does not get proccessed and I get this error:

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)

How can I encode the file so it gets proccessed? I thought # -*- coding: utf-8 -*- is enough. Or is there something I should set in the settings.py?

I looked at the code and error gets thrown when writing content to the file:

with open(new_path, 'w') as new_file:
    new_file.write(content)

So I doubt it's a django's fault.

Upvotes: 0

Views: 440

Answers (2)

davekr
davekr

Reputation: 2276

I used Django 1.4. This problem gets solved with Django 1.5. They updated the code and did exactly what catherine suggested.

Upvotes: 0

catherine
catherine

Reputation: 22808

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

Upvotes: 1

Related Questions