Reputation: 4929
I have two class-based views let's say, "Category" and "Product".
The thing I try to achieve is actually quite simple.
The "Category" contains a url (let's say "food") which means when I hit the url like this :
mydjango.com/myapp/food/
It actually searches in the database if there is any "Category" object having a url matching "food".
The url pattern is something like this :
url(r'^(?P<rel_url>.+)/$', login_required(is_allowed(Category.as_view())), name='category')
Now let's say I want to access a product (from the "Product" model) which is contained in the Category matchin "food" as url. For example :
mydjango.com/myapp/food/rice
The url field in the Product model looks like this then "food/rice"
Then my url pattern looks exactly the same as above except the name of the view.
The problem is, django only check the first url and tells me there is no Category object containing the 'food/rice' url. Which makes sense since that url is stored in the Product model.
Simpler question : How can I access two different views according to the pattern I match ?
mydjango.com/myapp/food
must use the Category view (using the rel_url)
mydjango.com/myapp/food/rice
doesn't match any Category, then it uses the Product view.
By the way I know this is not the good way, but this is the only solution I found (the application is far far more complicated than just Category/Product)
Upvotes: 0
Views: 122
Reputation: 197
You will need to differentiate based on the url pattern, and then simply move the more specific pattern first in you urls.py. The first pattern to match will be used.
That will lead you to something like:
url(r'^(?P<cat>[^/]+)/(?P<prod>[^/]+)/$', Product.as_view(), name='product')
url(r'^(?P<cat>.+)/$', Category.as_view(), name='category')
Upvotes: 1