Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An error with coding in Django 1.9.2

Tags:

python

django

I've created a model and two values in database. The first in Cyrillic and the second in Latin.

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

But when I try to click on link and edit the Cyrillic value I get an error.

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
like image 446
Vladyslav Krylasov Avatar asked Sep 26 '22 11:09

Vladyslav Krylasov


1 Answers

To use the __str__ method over __unicode__ in Python 2.7 use the provided python_2_unicode_compatible decorator:

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)

Otherwise you'll have to use __unicode__ over __str__.

like image 130
agconti Avatar answered Oct 03 '22 08:10

agconti