Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django URL template match (everything except pattern)

Tags:

django

I need a django regex that will actually work for the url router to do the following:

Match everything that does not contain "/api" in the route.

The following does not work because django can't reverse (?!

r'^(?!api)
like image 433
JayPrime2012 Avatar asked Jan 10 '14 21:01

JayPrime2012


1 Answers

The usual way to go about this would be to order the route declarations so that the catch-all route is shadowed by the /api route, i.e.:

urlpatterns = patterns('', 
    url(r'^api/', include('api.urls')),
    url(r'^other/', 'views.other', name='other'),
    url(r'^.*$', 'views.catchall', name='catch-all'), 
)

Alternatively, if for some reason you really need to skip some routes but cannot do it with the set of regexes supported by Django, you could define a custom pattern matcher class:

from django.core.urlresolvers import RegexURLPattern 

class NoAPIPattern(RegexURLPattern):
    def resolve(self, path):
        if not path.startswith('api'):
            return super(NoAPIPattern, self).resolve(path)

urlpatterns = patterns('',
    url(r'^other/', 'views.other', name='other'),
    NoAPIPattern(r'^.*$', 'views.catchall', name='catch-all'),
)
like image 174
Nicolas Cortot Avatar answered Sep 30 '22 04:09

Nicolas Cortot