【问题标题】:How to embed the results of my django app inside a template using something like {% include "app" %}?如何使用 {% include "app" %} 之类的东西将我的 django 应用程序的结果嵌入到模板中?
【发布时间】:2013-07-22 17:54:38
【问题描述】:

到目前为止,我已经能够创建一个项目并设置一个主页。到目前为止,我已经成功地设置了页面样式并设置了导航区域。我还创建了一个应用程序,它从我的数据库中提取类别名称列表并将其显示在右对齐列表中。当我将浏览器指向应用程序 url 时,它可以正常工作,但是当我尝试在我的项目中包含视图时,它会显示带有错误的基本面板,并且我传递给视图的字典似乎不可用。

这是我在浏览器中加载主页 url localhost:8000/ 时得到的结果:

这是我在浏览器中加载应用程序 url localhost:8000/categories/ 时得到的:

为什么我无法将应用程序的结果推送到我的模板中?两者似乎都可以工作,但不能一起工作?

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

我有另一个未解决的问题,其中包含相关的代码示例,但问题与我在这里提出的问题不同。

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

【问题讨论】:

  • 30 分钟前已编辑 Bill the Lizard -- 好奇...编辑了什么?

标签: python django templates views


【解决方案1】:

您需要在HomeView 中将类别查询集添加到您的上下文中。请记住,视图使用模板来构建响应 - 包括您也在不同视图 (IndexView) 中使用的模板不会导致与 IndexView 的任何交互。

HomeView 通过渲染模板来产生响应。如果该模板使用{% include %} 标记来拉入其他模板的片段,则这些片段将使用HomeView 建立的上下文呈现。您在IndexView 中所做的任何事情都不会对HomeView 产生任何影响,反之亦然。

继续通过类比字符串插值进行推理,假设您的模板是全局字符串变量而不是磁盘上的文件。你的情况是这样的:

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

使用 {% include %} 标签类似于字符串连接:

base_right_panel = base_right_panel + base_categories

那么你的两个观点是这样的:

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

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

除非您将categories 查询集添加到HomeView 的上下文中,否则在呈现响应时模板引擎将无法使用它。

您的HomeView 类应该包含您当前在IndexView 中拥有的get_context_data 方法。我不确定你是否真的需要IndexView,除非你想拥有一些只用类别列表服务于该页面的东西。

【讨论】:

  • 很好解释,这在几秒钟内解决了问题,ty! :) 所以基本上是因为我在应用程序中添加了类别,并且首先加载了 HomeView,在呈现页面之前数据从未进入 HomeView?
  • 类似的东西。 HomeView 是创建响应的对象 - 它接收请求对象并且必须返回 HttpResponse 实例。模板是视图可以用来执行此操作的一种工具,但它们没有任何特殊或绑定到 URL。返回 HttpResponse("Hello!") 也是合法的。对于初学者来说,基于类的视图可能有点太抽象了——我想你可能会发现使用基于函数的视图会更清楚。
猜你喜欢
  • 2020-08-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
  • 2012-01-04
相关资源
最近更新 更多