0

The components of the URLs of the Django app I'm working on are very 'pluggable', and different combinations of them get used in various urlpatterns, so our urls.py looks something like:

rev = r'(/R\.(?P<rev>\d+))?'
repo_type= r'^(?P<repo_type>svn|hg)/'
path = r'/dir/(?P<path>.*)$'
# etc.

urlpatterns = patterns('',
    (repo_type_param + r'view-source' + opt_rev_param + path_param, view_source),
    (repo_type_param + r'history' + path_param, history),
    (repo_type_param + r'revision' + opt_rev_param + r'/$', revision),
) #etc.

Which seems like a nice way to keep things clean. However, I found I kept getting NoReverseMatch errors when I tried to reverse any of the views pointed to by the urlpatterns. After a lot of tinkering, I found that using the full raw string in the pattern, rather than concatenating the substrings, fixed the problem.

So, is it really necessary to use only raw strings in urlpatterns? I couldn't find this documented anywhere. Bug or feature? Having to copy and paste regex patterns that get used repeatedly seems like a violation of DRY.

1
  • One of the things python likes to follow is being explicit over implicit - this might be a possible reason for not allowing the concatenation. Although I would be very surprised if there is not a way to do what you are after. :-) Commented Jul 4, 2010 at 8:42

3 Answers 3

1

I'm not sure about concatenation, but I know you can format raw strings and use them in urlpatterns. See BlogView.urlpatterns for an example.

Sign up to request clarification or add additional context in comments.

Comments

1

I found that this pattern works for redirects and might help in your case (unless I am interpreting your question incorrectly). I couldn't reverse a pattern within the same tuple but if I defined a new tuple and then concatenated a new tuple to the original Djanogo would reflect without issue. ex:

  urlpatterns = patterns('',
         ('^foo/$','foo.views.foo')
  )
  urlpatterns+= patterns('',('^$','django.views.generic.simple.redirect_to',{'url':reverse('foo.views.foo')}))

Comments

0

You can use a name to identify your url pattern like this:

urlpatterns = patterns('',
     url(repo_type_param + r'view-source' + opt_rev_param + path_param, view_source, name='myurlname'),
)

Note the url and name, and then reverse match like this:

reverse('myurlname', kwargs={'groupname': 'value'})

Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.