gpt4 book ai didi

python - Django 1.9.2 编码错误

转载 作者:太空狗 更新时间:2023-10-30 01:13:26 24 4
gpt4 key购买 nike

我在数据库中创建了一个模型和两个值。第一个是西里尔字母,第二个是拉丁文。

from __future__ import unicode_literals

from django.db import models

class Lecturer(models.Model):
fname = models.CharField('First name', max_length=200)
mname = models.CharField('Middle name',max_length=200)
lname = models.CharField('Last name', max_length=200)
pub_date = models.DateTimeField('Date published')

def __str__(self):
return "{} {} {}" .format(self.fname, self.mname, self.lname)

It seems work fine

但是当我尝试点击链接并编辑西里尔字母值时,出现错误。

UnicodeEncodeError at /admin/lecturers/lecturer/2/change/
'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
Request Method: GET
Request URL: http://localhost:8000/admin/lecturers/lecturer/2/change/
Django Version: 1.9.2
Exception Type: UnicodeEncodeError
Exception Value:
'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
Exception Location: /usr/local/lib/python2.7/dist-packages/django/utils/encoding.py in force_text, line 80
Python Executable: /usr/bin/python
Python Version: 2.7.6
Python Path:
['/home/vald/project',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-i386-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/pymodules/python2.7',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client']
Server time: Tue, 2 Feb 2016 20:30:07 +0200

最佳答案

要在 Python 2.7 中通过 __unicode__ 使用 __str__ 方法,请使用提供的 python_2_unicode_compatible装饰者:

from __future__ import unicode_literals

from django.db import models
from django.utils.encoding import python_2_unicode_compatible


@python_2_unicode_compatible
class Lecturer(models.Model):
fname = models.CharField('First name', max_length=200)
mname = models.CharField('Middle name',max_length=200)
lname = models.CharField('Last name', max_length=200)
pub_date = models.DateTimeField('Date published')

def __str__(self):
return "{} {} {}" .format(self.fname, self.mname, self.lname)

否则你将不得不使用 __unicode__ 而不是 __str__

关于python - Django 1.9.2 编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35161566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com