Django: Hierarchical URLs

How do you work with hierarchical URLs in Django? Any best practices for this? For instance. If I had a URL, for example /blog/category1/category2/myblogentry(using, for example, django-mptt), would you check in earlier urls.pyor pass the entire path to the view, let it check every part if it is a valid category, etc.? Doesn't sound so harsh, but just curious, can anyone recommend some best practices or can show good (general) solutions?

+3
source share
2 answers

I am afraid that there is no single answer to your question. The problem is that it says what the hierarchy looks like at the level of URL packages, there is too much logic with it.

I found it useful for decorator users. For example, in your case, you can write a decorator that checks the sanity of categories and passes only the final category down. Something like a decorator that can perform a function with this signature:

f(request, cat1, catN..., slug)

Verifying that each category is indeed the parent of the next, and passing the view to the category with final verification.

@validate_category_hierarchy
def post_in_category(request, category, slug):

If you really need it to be extensible, the decorator can do a little introspection and make some guesses (for example, how deep the tree can go, what other parameters are, etc.).

, , URL- confs, .      

+2

Source: https://habr.com/ru/post/1752914/


All Articles