0

I have django app, and have one problem: Category and page application have the same url:

Here is category.urls.py:

urlpatterns += patterns('',
    url('(?P<slug>[0-9A-Za-z-_.]+)/$', Category.as_view(), name='category')
)

And here is page.urls.py:

urlpatterns += patterns('',
   url(r'^(?P<slug>[0-9A-Za-z-_.]+)$', Page.as_view(), name='page')
)

So here is a problem - you can't open page with such urls, so i need this solution:

If here is exists Category with slug from url - open Category view, if there is no Category with such url, go to Page view.

But i don't know how to do this with RIGHT on django, without creating additional function like this:

def freeurl(request, slug):
   try:
      Category.objects.get(slug=slug)
      go to Category view
   except Category.DoesNotExists:
       go to Page view

is it possible ?

Vlad
  • 947
  • 1
  • 10
  • 24

2 Answers2

0

it's simple: include both urls.py with different prefix .)

main urls.py:

urlpatterns = patterns('',
    # ... snip ...
    (r'^category/', include('category.urls')),
    (r'^page/', include('page.urls')),
)

EDIT:

your proposition could look like this then:

def freeurl(request, slug):
    try:
        cat = Category.objects.get(slug=slug)
    except Category.DoesNotExist:
        try:
            page = Page.objects.get(slug=slug)
        except Page.DoesNotExist:
            raise Http404()
        else:
            return render_to_response('page.html', {'object': page}, context_instance=RequestContext(request))
    else:
        return render_to_response('cat.html', {'object': cat}, context_instance=RequestContext(request))

EDIT 2:

there's a project solving exactly your issue, check it out:

https://github.com/jacobian/django-multiurl

yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42
  • Thank you, i know. But i can't using prefix for both category and page view. That's why i ask this question.... – Vlad Mar 29 '13 at 10:22
  • so prefix it in directly in pattern isn't possible as well, I guess? Ie. `r'^category-(?P[0-9A-Za-z-_.]+)$'` for categories and `r'^page-(?P[0-9A-Za-z-_.]+)$'` for pages – yedpodtrzitko Mar 29 '13 at 10:59
  • no, this is not acceptable solutions too. i thought django have build in solution like i posted in my question – Vlad Mar 29 '13 at 13:18
  • i also edited my post w/ something you would consider acceptable – yedpodtrzitko Mar 29 '13 at 13:33
0
urlpatterns += patterns('',
    url(
        r'^category/(?P<slug>[0-9A-Za-z-_.]+)/$', 
        Category.as_view(), 
        name='category'
    )
)

urlpatterns += patterns('',
   url(
       r'^page/(?P<slug>[0-9A-Za-z-_.]+)/$', 
       Page.as_view(), 
       name='page'
   )
)
catherine
  • 22,492
  • 12
  • 61
  • 85
  • no, i can't add category/ and page/ word in URL. This is requirements from SEO department. – Vlad Mar 29 '13 at 10:20