Issue #21 closed

monkey-patch django.urlresolvers.resolve

frnhr
created an issue

django.urlresolvers.resolve doesn't work with localeurl (throws Resolver404).

This is quick-n-dirty monkey-patch in localeurl/models.py that works for me.

Warning: not tested, very quick, somewhat noobish :)

Is there a better way of using resolve()?

{{{ def resolve(*args, kwargs): lang=translation.get_language() path=args[0] if path.startswith("/%s/" % lang): path = path.replace("/%s/" % lang, '/', 1) args_list = list(args) args_list[0] = path args = tuple(args_list) return django_resolve(*args, kwargs) }}}

Used it with {{{patch_resolve()}}} in the very same way as for reverse:

{{{ django_resolve = None

def patch_resolve(): """ Monkey-patches the urlresolvers.resolve function. Will not patch twice. """ global django_resolve if urlresolvers.resolve is not resolve: django_resolve = urlresolvers.resolve urlresolvers.resolve = resolve

if settings.USE_I18N: patch_resolve()

}}}

Comments (12)

  1. Carl Meyer repo owner

    I'm going to leave this ticket open, but I don't plan to add this monkeypath to localeurl anytime soon, and hopefully never. I'd rather look at Django to see if it'd be possible to add hooks to the url resolver such that localeurl wouldn't have to monkeypatch anything. In the meantime anyone who needs this can use the above code in their own project.

  2. frol

    So for my project, I've added extra app (localeurl_ext) with empty __init__.py as usual and models.py with the following code:

    from django.conf import settings
    from django.core import urlresolvers
    from django.utils import translation
    from localeurl import utils
    
    
    def resolve(*args, **kwargs):
        locale = utils.supported_language(translation.get_language())
        path = args[0]
        if path.startswith("/%s/" % locale):
            path = path[len("/%s" % locale):]
        return django_resolve(path, *args[1:], **kwargs)
    
    django_resolve = None
    
    def patch_resolve():
        """
        Monkey-patches the urlresolvers.resolve function. Will not patch twice.
        """
        global django_resolve
        if urlresolvers.resolve is not resolve:
            django_resolve = urlresolvers.resolve
            urlresolvers.resolve = resolve
    
    if settings.USE_I18N:
        patch_resolve()
    
  3. Log in to comment