我尝试用MySQL设置Django,但发生了UnicodeDecodeError。 你能让我知道如何解决这个问题吗?我搜索了错误,但我无法理解。
我找到了这些代码并试过了,
def __unicode__(self):
return str(self.id) + ':' + self.name
和
def __str__(self):
return self.name.encode('utf8')
但我无法解决问题可能是因为我不知道如何使用def unicode ()而这些不适合我的列。
这是命令。
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.11
BuildVersion: 15A284
$ python —version
Python 2.7.10
$ brew install mysql memcached
$ sudo pip install django mysql-python
$ python
import django
print django.get_version()
1.8.5
$ cat /usr/local/etc/my.cnf
[mysql]
show-warnings
[mysqld]
character-set-server = utf8
$ mysql -u root -p
GRANT ALL PRIVILEGES ON *.* TO djuser@localhost IDENTIFIED BY ‘djpasswd’;
SHOW GRANTS FOR djuser@localhost;
CREATE DATABASE djdb CHARACTER SET utf8;
FLUSH PRIVILEGES;
USE djdb
SHOW TABLES;
Empty set (0.00 sec)
EXIT;
$ python manage.py validate
/Library/Python/2.7/site-packages/django/core/management/commands/validate.py:15: RemovedInDjango19Warning: "validate" has been deprecated in favor of "check".RemovedInDjango19Warning)
System check identified no issues (0 silenced).
$ python manage.py syncdb —database mydj
usage: manage.py syncdb [-h] [--version] [-v {0,1,2,3}] [--settings SETTINGS]
[--pythonpath PYTHONPATH] [--traceback] [--no-color]
[--noinput] [--no-initial-data] [--database DATABASE]
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 343, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 385, in run_from_argv
options = parser.parse_args(argv[2:])
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 64, in parse_args
return super(CommandParser, self).parse_args(args, namespace)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 1704, in parse_args
self.error(msg % ' '.join(argv))
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 68, in error
super(CommandParser, self).error(message)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/argparse.py", line 2374, in error
self.exit(2, _('%s: error: %s\n') % (self.prog, message))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 24: ordinal not in range(128)
以下是我的设置文件。
的myproject / settings.py
# encoding=utf8
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 1.8.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'e76ziss5nexm#bzsaruxd2ikap$zy=aoemzy&1%czm+z&)ru$x'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'myproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'mydj' : {
'ENGINE' : 'django.db.backends.mysql',
'NAME' : 'djdb', # DB名
'USER' : 'djuser',
'PASSWORD' : 'djpasswd',
'HOST' : 'localhost',
'PORT' : '3306',
'OPTIONS' : {'read_default_file' : '', 'init_command' : 'SET storage_engine=INNODB', },
'DEBUG' : True,
'DEFAULT_CHARSET' : 'utf-8',
},
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'jp-JP'
TIME_ZONE = 'Asia/Tokyo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
INSTALLED_APPS += (
'myapp', # アプリケーション
'debug_toolbar', # デバッグ
)
DEFAULT_CHARSET = 'utf-8'
FILE_CHARSET = 'utf-8'
的myapp / models.py
# -*- coding: utf-8 -*-
from django.db import models
# Create your models here.
class myDB(models.Model):
title = models.CharField(max_length=25)
body = models.TextField()
c = models.DateTimeField(auto_now_add=True)
u = models.DateTimeField(auto_now=True)
当我使用centOS6时,我没有这种错误,尽管这些软件的版本不同。 如果您向我推荐一些解决方案或建议,我们将不胜感激。 谢谢。
PS。我是这个网站的新手,所以我不知道如何在这里正确询问。对不起。