Django Unicodeencodeerror When Displaying Formset: Ascii Codec Can't Encode Characters
Solution 1:
You're using Python 2.x. Under 2.x, models should either have a __unicode__
method rather than or in addition to a __str__
method, and each method should return the appropriate type (unicode for __unicode__
, encoded bytes for __str__
) or you should use the python_2_unicode_compatible
decorator if you're on a sufficiently recent version of Django. If you're planning to stay on 2.x for the immediately future, I'd recommend just writing __unicode__
methods and not bothering with the decorator since you're concatenating string representations and I'm not quite sure what it does with that.
Some relevant docs are:
https://docs.djangoproject.com/en/1.8/ref/utils/#django.utils.encoding.python_2_unicode_compatible
https://docs.djangoproject.com/en/1.8/topics/python3/#str-and-unicode-methods
Either way, you should avoid converting database values (which are passed around as Unicode object) without specifying the encoding. Generally it's easiest to just define a method that returns unicode, eg:
classCountry(models.Model):# as above, exceptdef__unicode__(self):
returnself.country_name
Or:
@python_2_unicode_compatibleclassCountry(models.Model):# as above, exceptdef__str__(self):
returnself.country_name
Similarly for your other models:
classCity(models.Model):
...
def__unicode__(self):
returnself.city_name + "," + unicode(self.country)
Or (untested, you might need to call unicode(self.country)
here as well):
@python_2_unicode_compatibleclassCity(models.Model):
...
def__str__(self):
return self.city_name + "," + str(self.country)
Post a Comment for "Django Unicodeencodeerror When Displaying Formset: Ascii Codec Can't Encode Characters"