问题
Let's say I have 3 django apps, app Country, app Social and app Financial.
Country is a 'master navigation' app. It lists all the countries in a 'index' view and shows details for each country on its 'details' view.
Each country's details include their Social details (from the social app) and their Financial details (from the financial app).
Social and Financial both have a detail view (for each country)
Is there an elegant way to 'plug' in those sub-detail views into the master detail view provided by Countries? So for each country detail page I would see 2 tabs showing the social and the financial details for that country.
回答1:
2 common solution I use for this problem:
Partial Templates:
Create a template for rendering "social" and "financial" that does not need stuff from the view, other than the object it is working on (and uses the objects functions or template tags to render it).
then you can easily {% include %} it (and set the needed variable first).
This partial view does not render a full HTML page, but only a single DIV or some other HTML element you wish to use. If you also need a "social-only" page, you can create a page that renders the header and then includes the partial template. You can use a convention like _template.html for the partial template, and template.html for the regular template.
AJAX:
Make your "social" and "financial" views aware of being called in XMLHTTPRequest (request.is_ajax()). If they are, they return only a DIV element, without all the HTML around it. This way your master page can render without it, and add that content on the fly.
The AJAX way has several advantages: you don't render the plugin views on the same request as the whole page, so if you have many of these plugin views, the master page will load faster, and you can have a smart javascript choose only the relevant plugin views to ask for.
Also, you can use the normal view to generate data you need in the template (which you can't really do in the Partial Templates method).
来源:https://stackoverflow.com/questions/2249285/django-master-detail-view-plugins