<p>将所有类压缩为从<a href="https://docs.djangoproject.com/en/dev/topics/class-based-views/mixins/#context-and-template-responses" rel="nofollow">^{<cd1>}</a>继承的单个类,就像<a href="https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-display/#detailview" rel="nofollow">^{<cd2>}</a>一样,(还要检查<a href="https://docs.djangoproject.com/en/1.5/topics/class-based-views/mixins/#context-and-template-responses" rel="nofollow">^{<cd3>}</a>)并重写它的<code>get_template_names()</code>方法以返回适合当前情况的模板。在</p>
<p>一个很好的例子是在<a href="https://github.com/Fantomas42/django-blog-zinnia/blob/7863dea25557dd982a8371722a664d87ead2737b/zinnia/views/mixins/templates.py#L37" rel="nofollow">django-blog-zinnia</a>项目中</p>
<pre><code>def get_template_names(self):
"""
Return a list of template names to be used for the view.
"""
model_type = self.get_model_type()
model_name = self.get_model_name()
templates = [
'zinnia/%s/%s/entry_list.html' % (model_type, model_name),
'zinnia/%s/%s_entry_list.html' % (model_type, model_name),
'zinnia/%s/entry_list.html' % model_type,
'zinnia/entry_list.html']
if self.template_name is not None:
templates.insert(0, self.template_name)
return templates
</code></pre>
<p>Django将获取该名称列表并尝试每个项,以查看它是否存在于templates文件夹中。如果是,则使用该模板。在</p>
<h2>更新</h2>
<p>在仔细研究代码之后,可能是这样的:</p>
<h3>在你的主要网址.py</h3>
^{pr2}$
<p><code>DetailView</code>在设置了类属性<code>model</code>之后,将检查<code>slug</code>是否在url的kwargs中,如果是,它将使用slug进行模型查找,就像您正在做的一样:<code>Article.ojects.get(slug=self.kwargs['slug'])</code></p>
<h3>在模型.py</h3>
<p>您可以将<code>type</code>字段添加到<code>Article</code>模型中。类型将指定它是什么类型的文章。例如,您的<code>ChildrenView</code>、<code>YouthView</code>和<code>AdultView</code>的类型都可以是<code>music</code>(因为模板都是音乐,所以我假设它们是这样关联的)。在</p>
<pre><code>ARTICLE_TYPE_CHOICES = (
(0, 'music'),
(1, 'weddings'),
(2, 'outreach'),
...
)
class Article(models.Model):
...
type = models.IntegerField(choices=ARTICLE_TYPE_CHOICES)
...
</code></pre>
<h3>那么,在你的视图.py</h3>
<pre><code>class SuperSpecialAwesomeView(DetailView):
template_name = None
model = Article
def get_template_names(self):
slug = self.kwargs.get('slug', '')
templates = [
# create a template based on just the slug
'{0}.html'.format(slug),
# create a template based on the model's type
'{0}.html'.format(self.object.get_type_display()),
]
# Allow for template_name overrides in subclasses
if self.template_name is not None:
templates.insert(0, self.template_name)
return templates
</code></pre>
<p>给定一个类型为<code>music</code>和一个<code>ministry/children</code>的文章实例,Django将查找名为<code>ministry/children.html</code>的模板和名为<code>music.html</code>的模板。在</p>
<p>如果您需要为其他视图做一些特殊的事情(比如您可能需要为<code>SermonsView</code>)做一些特殊的工作,那么子类<code>SuperSpecialAwesomeView</code></p>
<pre><code>class SermonsView(SuperSpecialAwesomeView):
paginate_by = 2
queryset = Article.objects.order_by('-publish_date')
</code></pre>