user175678
user175678

Reputation: 23

Django url.py Different view functions with the same regex name pattern

I'm filtering a few categories (cat1, cat2, cat3) to be rendered by different views then all the rest by other view functions. It is getting unwieldy to keep adding category slugs to the urlpatterns each time one is added. Can I factor that part out of the regex some how?

urlpatterns = patterns('catalog.category_views',
    (r'^(?P<cat_slug>(cat1|cat2|cat3))/$', 'universal_category'),
    (r'^(?P<cat_slug>(cat1|cat2|cat3))/(?P<subcat_slug>[-\w]+)/$', 'subcat_listing'),
    (r'^(?P<cat_slug>(cat1|cat2|cat3))/part/(?P<part>[-\w]+)/$', 'subcat_product'),
)

urlpatterns += patterns('catalog.make_views',
    (r'^(?P<cat_slug>[-\w]+)/$', 'category'),
    (r'^(?P<cat_slug>[-\w]+)/(?P<make_slug>[-\w]+)/$', 'make'),
    (r'^(?P<cat_slug>[-\w]+)/(?P<make_slug>[-\w]+)/(?P<model_slug>[-\w]+)/(?P<year_low>\d{4})-(?P<year_high>\d{4})/$', 'listing'),
    (r'^(?P<cat_slug>[-\w]+)/part/(?P<part>[-\w]+)/$', 'product'),
)

Upvotes: 2

Views: 1204

Answers (1)

Zach
Zach

Reputation: 19082

I'd personally put this logic in the view rather than the urlspatterns.

I would create a list of all the special categories so for this:

special_cats = ['cat1','cat2','cat3']

Then for you view you can do something like this:

def generic_cat_view(request, cat_slug):
    if cat_slug in special_cats:
        return special_view(request, cat_slug)
    else:
        #generic view

Then when you add a new special category, you just need to add it to that list

Upvotes: 4

Related Questions