How to embed the results of my django app inside a template using something like {% include “app” %}?

筅森魡賤 提交于 2020-01-31 18:27:20

问题


So far I have been able to Create a project and setup a Homepage. So far I have had success with styling the page and getting my nav areas setup. I have also created an app that pulls a list of category names from my database and displays it in a right-justified list. When I point my browser to the app url, it works perfectly, but when I try to include the view in my project it displays the base panel with an error, and the dictionary I passed to the view does not appear to be available.

This is what I get when I load the home url localhost:8000/ in my browser:

This is what I get when I load the app url localhost:8000/categories/ in my browser:

Why am I not able to push the results of my app into my template? Both appear to work but not together?

base_right_panel.html

{% block content %}
  <div style="float: right;">
    <div id="base_categories" style="margin: 10px; padding-bottom: 10px;">
      {% block base_categories %}
        {% include "base_categories.html" %}
      {% endblock %}
    </div>
  </div>
{% endblock %}

base_categories.html

{% block content %}
  <div class="section" style="float: right;">
    <h4 class="gradient">Category List</h4>
    <ul>
      {% if categories %}
        {% for category in categories %}
          <li><a href="" id="nav_font">{{ category.title }}</a></li>
        {% endfor %}
      {% else %}
        <p>no data! {{ categories|length }}</p>
      {% endif %}
    </ul>
  </div>
{% endblock %}

CategoryList/views.py

from django.views.generic import TemplateView
from CategoryList.models import CategorylistCategorylist #<-- Changed to match inspectdb result

class IndexView(TemplateView):
    template_name="base_categories.html" #<-- Changed name from index.html for clarity

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        context["categories"] = CategorylistCategorylist.objects.all()
        return context

CategoryList/models.py

from django.db import models

class CategorylistCategorylist(models.Model): #<-- Changed to match inspectdb
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=255L, unique=True)
    base_url = models.CharField(max_length=255L, unique=True)
    thumb = models.ImageField(upload_to="dummy", blank=True) #<-- Ignored inspectdb's suggestion for CharField

    def __unicode__(self):
        return self.name

    # Re-added Meta to match inspectdb
    class Meta:
        db_table = 'categorylist_categorylist'

CategoryList/urls.py

from django.conf.urls.defaults import patterns, url, include
from django.contrib import admin
from django.conf import settings
from CategoryList import views

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='base_categories'),
)

if settings.DEBUG:
    urlpatterns = patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
    url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns

MySite/urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from home import views as home_view
from CategoryList import views as index_view

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', home_view.HomeView.as_view(), name="home"),

    url(r'^categories/$', index_view.IndexView.as_view(), name='base_categories'),#include('CategoryList.urls')),

    url(r'^admin/', include(admin.site.urls)),
    #url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
)

if settings.DEBUG:
    urlpatterns = patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
    url(r'', include('django.contrib.staticfiles.urls')),
) + urlpatterns

I have another open question which has the relevant code examples but the question differs from what I am asking here.

Is there a simple way to display mysql data in Django template without creating an app?


回答1:


You need to add the category queryset to your context in your HomeView. Remember, the view uses the templates to build the response - including a template that you also use in a different view (IndexView) does not cause any interaction with IndexView.

HomeView produces its response by rendering a template. If that template uses {% include %} tags to pull in pieces of other templates, those pieces will be rendered using the context established by HomeView. Nothing you do in IndexView has any effect on HomeView, and vice versa.

Continuing to reason by analogy to string interpolation, pretend your templates are global string variables instead of files on disk. Your situation is something like this:

base_categories = "My categories are: %(categories)s."
base_right_panel = "This is the right panel.  Here are other fields before categories."

Using the {% include %} tag is something like string concatenation:

base_right_panel = base_right_panel + base_categories

Then your two views are analogous to this:

def home_view(request):
    context = {}
    return base_right_panel % context

def index_view(request)
    context = {'categories': ['a', 'b', 'c']}
    return base_categories % context

Unless you add the categories queryset to the context in HomeView, it will not be available to the template engine when rendering the response.

Your HomeView class should include the get_context_data method that you currently have in your IndexView. I am not sure you actually need IndexView at all, unless you want to have something that serves that page with just the categories list.



来源:https://stackoverflow.com/questions/17794168/how-to-embed-the-results-of-my-django-app-inside-a-template-using-something-like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!