5

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)
JayPrime2012
  • 2,672
  • 4
  • 28
  • 44

3 Answers3

8

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'),
)
Nicolas Cortot
  • 6,591
  • 34
  • 44
0

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

Aaron Lelevier
  • 19,850
  • 11
  • 76
  • 111
  • 2
    The OP stated this does not work. The docstring for [normalize](https://github.com/django/django/blob/1.6/django/utils/regex_helper.py#L46) does indeed state: (6) Raise an error on all other non-capturing (?...) forms (e.g. look-ahead and look-behind matches) and any disjunctive ('|') constructs. – Nicolas Cortot Jan 11 '14 at 02:14
0

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

Community
  • 1
  • 1