title: reusing views inside other views in Django
body: <p>I have a few components on my website that appear on many pages. DRY in mind, I would like to factor them out in separate snippets that I can include in the views that need them. </p>
  
  <p>If it were only static items, then an <code>{% include "snippet.html" %}</code> would be the perfect solution. How can achieve a similar thing for snippets that include forms (and hence logic in the view) or require calculations before being displayed? Also, I would like to be able to nest the snippets several levels deep.</p>
  
  <p>I know I can put simple logic in the template, using <code>{% if ... %} ... {% endif %}</code> blocks, but this turns into horrible spagetthi very soon and I want to keep the business logic separated from the presentation logic.</p>
  
  <p>I am imagining a pattern as follows (here with oversimplified business logic):</p>
  
  <pre><code>def view1(request):
      "Display some data"
      total = get_total_vote_count()
      return render(request, 'snippet1.html', {'total': total})
  
  def view2(request, pk):
      "Display some data about the article with primary key pk."
      votes = get_votes_for_article(pk)
      render1 = view1(request)
      return render(request, 'snippet2.html', {'votes': votes, 'render1': render1})
  
  def view3(request, pk):
      "Display article pk and some additional data from view1 and view2":
      article = get_object_or_404(Article, pk=pk)
      render2 = view2(request, pk)
      return render(request, 
                    'article.html', 
                    {'article': article, 'render2': render2},
                    )
  </code></pre>
  
  <p>with the templates something like:</p>
  
  <pre><code># in snippet1.html:
  &lt;a href="overview.html"&gt;{{ total }}&lt;/a&gt;
  
  # in snippet2.html:
  &lt;p&gt;Votes for this article: {{ votes }} out of {{ render1 }} total votes.&lt;/p&gt;
  
  # in page.html:
  {% extends "base.html" %}
  {% block "content" %}
    &lt;h1&gt;article.title&lt;/h1&gt;
    &lt;p&gt;article.text&lt;/p&gt;
    &lt;small&gt;{{ render2 }}&lt;/small&gt;
  {% end block "content" %}
  </code></pre>
  
  <p>Note that there will be more views that will use <code>view1</code> and <code>view2</code> (e.g. an overview of the votes for all articles); that is why I have factored them out in separate functions.</p>
  
  <p>How can I make this work? 
  Or is there a better trick in the Django toolbox to make this work without repeating view1 and view2 every time I want to use the same snippets in other views?</p>