开发者

Using variables in Django urlpatterns

开发者 https://www.devze.com 2023-01-05 10:57 出处:网络
The components of the URLs of the Django app I\'m working on are very \'pluggable\', and different combinations of them get used in vario开发者_StackOverflow社区us urlpatterns, so our urls.py looks so

The components of the URLs of the Django app I'm working on are very 'pluggable', and different combinations of them get used in vario开发者_StackOverflow社区us 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.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消