JayPrime2012
JayPrime2012

Reputation: 2692

Django URL template match (everything except pattern)

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)

Upvotes: 5

Views: 5549

Answers (3)

André Almeida
André Almeida

Reputation: 53

I had this problem integrating django with react router, I check this link to fix it.

decoupled frontend and backend with Django, webpack, reactjs, react-router

Upvotes: 0

Nicolas Cortot
Nicolas Cortot

Reputation: 6701

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'),
)

Upvotes: 8

Aaron Lelevier
Aaron Lelevier

Reputation: 20810

Use a negative look behind like so:

r'^(?!/api).*$'

This link explains how to do that:

http://www.codinghorror.com/blog/2005/10/excluding-matches-with-regular-expressions.html

Upvotes: 0

Related Questions