解決Django的admin界面中文亂碼
問題陳述
最近在做一個很小的Django項目時,使用了自帶的sqlite作為數據庫。后台admin界面在顯示中文數據時,總會遇到亂碼。這里截取一小部分代碼:
models.py文件
# _*_ coding:utf-8 _*_
from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse
# Create your models here.
class FatherMenu(models.Model):
title = models.CharField(u"菜單名", max_length=20)
slug = models.CharField(u"鏈接", max_length=100, db_index=True)
son = models.BooleanField("子菜單?", default=False)
class Meta:
verbose_name = u"一級菜單"
verbose_name_plural = u"一級菜單"
def __str__(self):
return self.title
導入數據data.json,例如:
[
{
"model":"seclab.FatherMenu",
"pk":1,
"fields":
{ "title":"首頁", "slug":"/", "son":0 } },
{
"model":"seclab.FatherMenu",
"pk":2,
"fields":
{ "title":"概況", "slug":"/introduction/", "son":0 } },
{
"model":"seclab.FatherMenu",
"pk":3,
"fields":
{ "title":"動態", "slug":"/dynamic/", "son":1 } }
]
from django.contrib import admin
# Register your models here.
from models import *
class FatherMenuAdmin(admin.ModelAdmin):
list_play = ('title', 'slug', 'son')
admin.site.register(FatherMenu, FatherMenuAdmin)
導入數據、創建superuser、運行server
python manage.py makemigrations
python manage.py migrate
python manage.py loaddata fatherMenu.json
python manage.py createsuperuser --username admin --email blank
python manage.py runserver 0.0.0.0:8080
登入到后台的admin界面,假設查看一級菜單->首頁
,就會報錯:
UnicodeEncodeError at /admin/seclab/fathermenu/1/change/
'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
Unicode error hint
The string that could not be encoded/decoded was: 首頁
解決
試了幾次發現,只要在models.py
中,每個__self__
函數返回的字段包含中文,就會在admin界面引發上述UnicodeEncodeError
。
具體到本例,__self__
函數返回了self.title
,表示菜單名,而導入數據時每個title
字段都是像首頁、概況、動態這樣的中文。
搜到了兩種解決方法,可以任選一種:
1.用__unicode__
函數代替__str__
原先寫的模型代碼中的方法用提 def __str__(self):
這個是舊版本中用的方法,在Django 0.96以后的版本中,應該換成 def __unicode__(self):
, 這樣就解決了字符串傳遞時出錯的問題,統一編碼為Unicode字符串。
class FatherMenu(models.Model):
···
def __unicode__(self):
return self.title
引自:Django報錯UnicodeEncodeError: 'ascii' codec can't encode characters 之解決方法
2.使用sefdefaultencoding
函數
# _*_ coding:utf-8 _*_
from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse
# Create your models here.
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class FatherMenu(models.Model):
···
引自:解決Python2.7的UnicodeEncodeError: ‘ascii’ codec can’t encode異常錯誤