views:

38

answers:

1

Hi All,

Most views in my project accept an optional username parameter and if exists, filter the querysets passed to the templates for that user. So, for example:

the index view handles both the following url patterns:

'^$' # general index page
'^(?P<username>[-\w]+)/$' # index page for the user

'^photos/$' # photo index page
'^(?P<username>[-\w]+)/photos/$' # photos for that user
...

As there are a number of such applications, it doesn't seem very DRY to implement the same logic by replicating the patterns. I thought it may be possible to recursively include the main urls.py module, so I did this:

url(r'^(?P<username>[-\w]+)/', include('urls')),

My reasoning was that, when an other urls module is included, the matched pattern is removed from the path. So, I was hoping that

'^(?P<username>[-\w]+)/photos/$'

would become

'^photos/$'

when it is matched by the recursively included urls module, with the extra username parameter. But this caused the development server to die silently when a request is made.

The second approach I can think of is to write a middleware, which would match the pattern in the url, if exists, and add the viewed user to the request and remove the part that matches the username from the request path. But I don't want to mess with the path as this may have unpredictable results.

What would you recommend? Am I too picky for DRYness?

Thanks, oMat

+1  A: 

Just define the regex as a string in the same file and use the string concatenation already!

user_regex = r"^(?P<username>[-\w]+)/"

Then you can do regex '%s/photos$'%user_regex so that you keep the regex defined only once, very dry.

Altho', your reasoning for including the urls.py patterns within the url tag is right and I'm not sure why it failed. Perhaps some other error?

Lakshman Prasad
thanks, it will help cleaner patterns but in the actual case, each application has its own urls.py file which are included. so, for each application, all patterns should be replicated in their own urls.py with their alternatives that matches the username.
omat
apart from the repetition, because the app urls are included as `(r'^photo/', include('photos.urls'))`, the url for users photos would be `/photo/[username]/`.
omat