Django Url Conf Dynamic Url Conflict

413 Views Asked by At

So I have two models in the same app that have pretty much identical url structures:

urlpatterns = patterns('',
    #....
    url(r'^prizes/', include(patterns('prizes.views',
        url(r'^$', 'PrizeStore_Index', name="prizestore"),
        url(r'^(?P<slug>[\w-]+)/$', PrizeCompanyDetailView.as_view(), name="prizecompany"),
        url(r'^(?P<slug>[\w-]+)/$', 'PrizeType_Index', name="prizetype"),
        url(r'^(?P<company>[\w-]+)/(?P<slug>[\w-]+)/$', 'PrizeItem_Index', name="prizepage"),
    ))),
    # Old Redirects
)

The problems here being Reviews and PrizeType. I want my urls structured so that a user looking for prizes under a certain category goes to /prizes/prizetype. But if they want to see prizes under a certain company, then they'd go to /prizes/companyslug/. However, these two urls will naturally conflict. I can always just change the url structure, though I'd rather not. I just want to know if there are any ways around this that don't involve changing the url structure.

2

There are 2 best solutions below

1
On BEST ANSWER

I would suggest writing a helper view function, which checks whether the inputted url corresponds to a company or a category, and then redirecting the request to the appropriate page.

url(r'^prizes/', include(patterns('prizes.views',
    url(r'^$', 'PrizeStore_Index', name="prizestore"),
    url(r'^(?P<slug>[\w-]+)/$', prizehelper, name="prizehelper),

where, you can check within prizehelper, if it is a company or a category and move on accordingly.

Another approach could be, to change your url structure, and reflect which type of url it is

url(r'^prizes/', include(patterns('prizes.views',
    url(r'^$', 'PrizeStore_Index', name="prizestore"),
    url(r'^company/(?P<slug>[\w-]+)/$', PrizeCompanyDetailView.as_view(), name="prizecompany"),
    url(r'^category/(?P<slug>[\w-]+)/$', 'PrizeType_Index', name="prizetype"),
0
On

Have a single urlconf entry that goes to a view which figures out which type is being examined and then dispatches to the appropriate view for that type.