[Django]-Django: How do I override app-supplied urls in my project urlconf?

46👍

Apparently duplicate URLs are allowed in the urlconf, and the first match listed will have priority:

urlpatterns = patterns('',
  (r'^$', include('glue.urls')),
  (r'^foo/', include('foo.urls')),

  # This will override the same URL in bar's urlconf:
  (r'^bar/stuff/$', 'glue.views.new_bar_stuff', {'arg': 'yarrgh'}, 'bar_stuff'),

  (r'^bar/', include('bar.urls')),
)

4👍

It is not clear what you are asking, but as I understand it, your question is:

What’s the most elegant way to pass the alternate template to the view
in bar?

This has nothing to do with the url conf, which just maps URLs to methods.

Templates in django are looked up from locations in TEMPLATE_DIRS in your settings.py, and most importantly django will stop looking once it finds a template.

If your TEMPLATE_DIRS is blank (as is the default), then django will look for templates in a templates directory inside any registered apps (apps listed in INSTALLED_APPS).

So, to pass an alternate template to any application, simply create a file with the same name (and directory structure) in a directory that is listed in TEMPLATE_DIRS. Django will search this first, and stop when it finds a match.

This is the same way you override default admin templates.

For your particular case, suppose you want to pass an alternate version of index.html to the app bar.

Create a directory override_templates somewhere in your project path.

Inside that create bar/templates/ directory, and add your customized index.html to this directory, so you have override_templates/bar/templates/index.html.

Add the full path to override_templates to TEMPLATE_DIRS in settings.py.

Now django will first search your custom directory for any templates requested, and will load your alternate index.html.

Leave a comment