Steve Bennett
Steve Bennett

Reputation: 126537

How can two apps respond to the same URL in Django?

I think I'm missing a basic concept here. In the stereotypical Django project, you'd have two apps responding to different urls:

http://localhost/myproj/app1/33
http://localhost/myproj/app2/newcomment.html

But what mechanisms exist to handle cases where the two apps are complementary - say one provides content, and the other provides presentation? Or maybe one is content and the other is a kind of static, side-wide content that should appear on every page.

In particular, I don't understand how both apps can use template inheritance to extend the same template. Imagine there's a base app "baseapp" with a template "base.html":

...
<div blah blah>
{% block content %}
{% endblock %}
...

App1 extends it:

{% extends "baseapp/templates/base.html" %}

{% block content %}
... here's the actual content...
{% endblock %}

App2 adds a little banner or something:

{% extends "baseapp/templates/base.html" %}

{% block content %}
<div class="banner">Please support our site!</div>
{{ block.super }}
{% endblock %}

So what are the ways that both templates can get displayed? I can think of:

  1. app1 could extend app2's templates. But this seems wrong: app1 is the content provider, and shouldn't be dependent on something as trivial as app2.
  2. app2 could extend app1's templates. But this seems wrong: now the URL scheme would have to funnel every URL through app2 (if I understand correctly)
  3. middleware?

As I said, I'm probably missing something very basic. Or I'm making some very faulty assumptions that I don't know about. (This question is my third attempt, after Embed an optional Django application in another page, if that app is present and How to capture and display information external to my webapp, but relevant to users of it? - I'm having trouble framing the issue.)

Upvotes: 0

Views: 220

Answers (2)

Steve Bennett
Steve Bennett

Reputation: 126537

I think what I was actually missing here:

  • Apps can override templates just by including a template of the right name in the right subdirectory. The Django docs don't make this very clear, that I can see: they refer to this functionality in the context of Admin templates
  • When overriding a template as above, you can't extend it, but:
  • This snippet lets you both override a template and extend it: http://djangosnippets.org/snippets/1376/

Here's a closely related question: Django: Overriding AND extending an app template

Upvotes: 0

DrTyrsa
DrTyrsa

Reputation: 31981

App doesn't respond to an URL, a view does. View is a function that can use models, forms and other object from any app. There isn't any problem here.

If you want to add something to template, inheritance isn't the only way. You'd better use custom context processor or custom template tag.

Upvotes: 2

Related Questions