0

I am using modeltranslation in my project, and my goal is to also translate the slugs of my urls.

The slugs are successfully translated and I overwrote the save method of my Model to automatically populate the slug fields for all the languages in my project.

class FrontendCategory(models.Model):
    name = models.CharField(_('Name'), max_length=255, db_index=True)
    slug = AutoSlugField(_('Slug'), populate_from='name', max_length=255, db_index=True)

    def save(self, *args, **kwargs):
        for lang_code, lang_verbose in settings.LANGUAGES:
            if hasattr(self, 'slug_%s' % lang_code) and hasattr(self, 'name_%s' % lang_code):
                setattr(self, 'slug_%s' % lang_code, slugify(getattr(self, 'name_%s' % lang_code, u"")))

   def get_absolute_url(self):
       url = reverse(
            'catalogue:frontend-category',
            kwargs={'frontend_category_slug': self.slug, 'pk': self.pk})
       return url

I checked and all the slugs are translated and saved correctly in the database.

this is my url:

url(r'^section/(P<frontend_category_slug>[\w-]+(/[\w-]+)*)_(?P<pk>\d+)/$',
                self.frontend_category_view.as_view(), name='frontend-category'),

if I call the get_absolute_url method in a template the following error gets raised:

Reverse for 'frontend-category' with arguments '()' and 
keyword arguments '{'pk': 5, 'frontend_category_slug':'test-slug'}' not found. 
1 pattern(s) tried: ['de/catalogue/section/(P<frontend_category_slug>[\\w-]+(/[\\w-]+)*)_(?P<pk>\\d+)/$']

which seams weird because it is exactly what I seem to have defined in my url definition. All of this was working before I translated the slug with modeltranslation. Is there some kind of slug lookup performed by the url definition? Am I missing something else?

matyas
  • 2,696
  • 23
  • 29
  • How about if you put this inside the `get_absolute_url`: `from django.utils import translation` and `lang = translation.get_language()` and `with translation.override(lang): url = reverse(...) return url` ?? – nik_m Apr 12 '17 at 12:12
  • thank you for the input but I realized that it had nothing to do with modeltranslation per se, I messed up the regex while editing my code – matyas Apr 12 '17 at 13:08

1 Answers1

0

It turns out that my problem had nothing to do with modeltranslation and languages, while I was editing my code I accidentally edited my url definition which caused this error.

url(r'^section/(P<frontend_category_slug>[\w-]+(/[\w-]+)*)_(?P<pk>\d+)/$',
                self.frontend_category_view.as_view(), name='frontend-category'),

should be

url(r'^section/(?P<frontend_category_slug>[\w-]+(/[\w-]+)*)_(?P<pk>\d+)/$',
        self.frontend_category_view.as_view(), name='frontend-category'),

(missing questionmark befor P):

?P<frontend_category_slug>
matyas
  • 2,696
  • 23
  • 29