2

我使用 Django 创建了一个非常简单的示例代码,但无法让模型值显示在我的页面上:

----------------------------- 主页/models.py

from django.db import models

class Home(models.Model):
    msg = models.CharField(max_length=100)

    @classmethod
    def create(cls, msg):
        home = cls(msg=msg)
        # do something with the book
        return home

home = Home.create("Hello World!")

------------------------------------home/views.py

from django.views.generic import TemplateView
from project.models import Home

class IndexView(TemplateView):
    model = Home
    template_name = 'home/index.html'

------------------------------------------ 模板/home/index.html

{{ home.msg }}
this is a test page. I am expecting to see this....

------------------------------------------------------- urls.py

from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView

admin.autodiscover()

urlpatterns = patterns('',
    # Home pagetentacl.urls
    url(r'^$', TemplateView.as_view(template_name='home/index.html')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

-------------------------------------- 浏览器上的结果页面:

这是一个测试页面。我期待看到这个......


对于我的示例,我不想拥有数据库访问权限。我希望我的模型返回“hello world”字符串。index.html 上的 home.msg 不返回任何内容。这里缺少什么?

4

2 回答 2

1

您没有为模板提供Home. 您需要创建一个并将其作为上下文传递给模板,格式为{'msg': msg}.

编辑:添加一些代码

首先,您应该home在您的视图中创建您的实例。我从未使用过TemplateViews,所以我将使用常规视图方法。

def IndexView(request):
    home=Home.create("Hello World!")

    return render(request, 'index.html', {'home': home},)
于 2013-08-09T18:03:22.150 回答
0

As @Daniel rightly points out, you're not giving your template an instance of Home to work with.

If you want to use class-based views, subclass TemplateView and override get_context_data():

class IndexView(TemplateView):

    template_name = "home/index.html"

    def get_context_data(self, **kwargs): 
        context = super(HomePageView, self).get_context_data(**kwargs)
        context["home"] = Home.create("Hello World!")
        return context

And make sure your urls.py is using IndexView.as_view() - your version above is just referencing the generic TemplateView.

The fact that you added a model field to your subclass of TemplateView makes me think you're confusing it with DetailView. See the documentation for the difference.

于 2013-08-09T19:52:59.763 回答