SoFunction
Updated on 2024-11-17

Ways to handle specific URLs in URLconf in the Django framework

Sometimes you have a pattern for handling a series of URLs in your URLconf, but sometimes you need to handle one of those URLs in particular. In that case, use the linear processing that puts the special case first in the URLconf .

Let's say you consider adding a target page to Django's administration site in the way described by the following URLpattern

urlpatterns = patterns('',
  # ...
  ('^([^/]+)/([^/]+)/add/$', views.add_stage),
  # ...
)

This will match URLs like /myblog/entries/add/ and /auth/groups/add/. However, the page for adding user objects (/auth/user/add/) is a special case because it does not show all the form fields, it shows the two password fields and so on. We can address this situation by specifying it in the view:

def add_stage(request, app_label, model_name):
  if app_label == 'auth' and model_name == 'user':
    # do special-case code
  else:
    # do normal code

However, as we've mentioned several times in this chapter, this is not elegant: it puts the URL logic in the view. A more elegant solution is to take advantage of the top-down parsing order of URLconf:

urlpatterns = patterns('',
  # ...
  ('^auth/user/add/$', views.user_add_stage),
  ('^([^/]+)/([^/]+)/add/$', views.add_stage),
  # ...
)

In this case, requests like /auth/user/add/ will be handled by the user_add_stage view. Even though the URL also matches the second pattern, it will match the above pattern first. (This is short-circuiting logic.)