G
G
Gashington2014-02-12 11:56:04
Django
Gashington, 2014-02-12 11:56:04

How to fix "UnicodeDecodeError" error in Django?

Hello, I have a problem that I can't find a solution for a few days. I am making a CNC blog where categories and article titles are written /category/post Here are the models themselves

from django.db import models
from pytils import translit
from ckeditor.fields import RichTextField

class Alias(models.Model):
    title = models.CharField(u'Название', max_length=100)
    alias = models.SlugField(max_length=100, blank=True)

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.alias:
            self.alias = translit.slugify(self.title)
        super(Alias, self).save(*args, **kwargs)

    class Meta:
        abstract = True


class Category(Alias):
    pass

    def get_absolute_url(self):
        from django.core.urlresolvers import reverse_lazy
        return reverse_lazy('blog:category_posts_list', kwargs={'category_alias': self.alias})

    class Meta:
        verbose_name_plural = u"Категории"

class Post(Alias):
    publication_date = models.DateField(u'Дата публикации')
    content = RichTextField(u'Контент')
    category = models.ForeignKey(Category, verbose_name=u'Категория')
    tags = models.ManyToManyField(Tag, verbose_name=u'Метки')

    def get_absolute_url(self):
        from django.core.urlresolvers import reverse
        return reverse('blog:post_detail', args=[self.category.alias, self.alias])

    class Meta:
        verbose_name_plural = u"Записи"

For CNC, the category/article name is taken and transliterated. From the title written in Cyrillic, we get the Latin alias, which is then used in the url
Everything worked fine Until I decided to add breadcrumbs. For breadcrumbs, I used the django sitetree complex solution. Breadcrumbs actually cause the error UnicodeDecodeError 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128) if we go to a URL like /blog/kategorya If alias is initially set in Latin, for example category, then when going to the URL / blog/category everything works
fine
if sitetree_item.urlaspattern:
            url = sitetree_item.url
            view_path = url
            all_arguments = []

            if ' ' in url:
                view_path = url.split(' ')
                # We should try to resolve URL parameters from site tree item.
                for view_argument in view_path[1:]:
                    resolved = self.resolve_var(view_argument)
                    # In case of non-ascii data we leave variable unresolved.
                    if isinstance(resolved, six.text_type):
                        if resolved.encode('ascii', 'ignore').decode('ascii') != resolved:
                            resolved = view_argument
                        # URL parameters from site tree item should be concatenated with those from template.
                    all_arguments.append('"%s"' % str(resolved))  # Эта строка вызывает ошибку 
                view_path = view_path[0].strip('"\' ')

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Andrey K, 2014-02-13
@Gashington

Add this import very first.
from __future__ import unicode_literals

G
Gasoid, 2014-02-12
@Gasoid

why is it not in the model at first
# -*- coding: utf-8 -*-

B
BigAzat, 2014-02-12
@BigAzat

all_arguments.append('"%s"' % unicode(resolved))
did you not try it?
And try to change

class Alias(models.Model):
    title = models.CharField(u'Название', max_length=100)
    alias = models.SlugField(max_length=100, blank=True)

    def __unicode__(self):
        return u'%s' % (unicode(self.title))

A
alternativshik, 2014-02-12
@alternativshik

up

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question