How do you deal with hierarchical URLs in Django? Any best practices for that?
Eg. If I would have an URL like /blog/category1/category2/myblogentry
(using eg. django-mptt), would you do some checking before in urls.py
or give the whole path to a view, let it check every part if it is a valid category etc?
Doesn't sound so tough, but just curious if anybody can recommend some best practices or can show some good (generic) solutions?
views:
55answers:
1I fear there is no single answer to your question. The problem is that there specifing what the hierarchy looks like at the URL level bundles too much logic with it.
I've found useful to user decorators. For example, in your case you could write a decorator that checks the sanity of categories, and passed only the final category down the view. Something like a decorator that can take a function with this signature:
f(request, cat1, catN..., slug)
Checking that each category is indeed a parent to next one, and passing down the view the final checked category.
@validate_category_hierarchy
def post_in_category(request, category, slug):
If you really need it to be extensible, the decorator can do a bit of introspection and make some guesses (such as how deep can the tree go, what are the remaining parameters like, etc).
Then all you need to do is write your URL confs carefully, so that the decorator gets the parameters in good shape. pass