1

I'm trying to include optional URL patterns in my Django project by adapting the multiple-routes pattern explained in this SO post.

In my urls.py file I have the following patterns.

urlpatterns = [
    url(r'^(?P<slug>[-\w]+)\/?$', View.as_view()),
    url(r'^(?P<section>[-\w]+)\/(?P<slug>[-\w]+)\/?$', View.as_view()),
    url(r'^(?P<section>[-\w]+)\/(?P<tag>[-\w]+)\/(?P<slug>[-\w]+)\/?$',View.as_view()),
]

The parameters section, tag, and slug correspond to model fields. So a HTTP request to /foo/bar/baz returns a model instance with a "foo" section, "bar" tag, and "baz" slug. Not all model instances have a section or tag, those parameters are optional.

If you think about the URL dispatcher as a function with a domain of URLs and a codomain of model instances, the pattern I'm using isn't an injective function. /baz, /foo/baz, and /foo/bar/baz return the same model instance, but only the last URL should return the model instance.

In short, how do I configure my urlpatterns to return my foo-bar-baz model if, and only if, the requested URL is /foo/bar/baz?

Community
  • 1
  • 1
kas
  • 898
  • 3
  • 10
  • 27
  • why don't you just accept the url as one regex and then split it with / and do what you want to do? – binu.py May 16 '17 at 19:41

1 Answers1

0

I think this will be much easier to deal with in the view. In your view, I'd look at the request and if the URI is of the wrong form, then issue a redirect to the right URI. That's going to be much easier than trying to force this into the URL dispatcher.

Sam Hartman
  • 6,210
  • 3
  • 23
  • 40
  • You're right, I've been playing around with overwriting the `get_object` method in `SingleObjectMixin` and it looks like that's going to get me the desired behavior. Thanks! – kas May 17 '17 at 20:07