如何将对象传递给 TemplateView?

Dan*_*Dan 1 django django-templates

我刚刚学习 CBV,并且在将对象传递给 TemplateView 时遇到了困难。这非常令人沮丧,因为我知道这应该是非常基本的。

这是我的观点.py:

from __future__ import absolute_import
from django.views import generic
from company_account.models import CompanyProfile

class CompanyProfileView(generic.TemplateView):
    template_name = 'accounts/company.html'

    def get_context_data(self, **kwargs):
        context = super(CompanyProfileView, self).get_context_data(**kwargs)
        return CompanyProfile.objects.all()
Run Code Online (Sandbox Code Playgroud)

这是我的 Models.py:

from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

class CompanyProfile(models.Model):
    company_name = models.CharField(max_length=255)

    def __str__(self):
        return self.company_name
Run Code Online (Sandbox Code Playgroud)

这是 urls.py

urlpatterns = [
    url(r'^accounts/companyprofile/$', CompanyProfileView.as_view()),
]
Run Code Online (Sandbox Code Playgroud)

最后,这是模板:

{% extends '_layouts/base.html' %}

{% block title %}Company Profile{% endblock %}

{% block headline %}<h1>Company Profile</h1>{% endblock %}

{% block content %}{{ CompanyProfile.company_name }}{% endblock %}
Run Code Online (Sandbox Code Playgroud)

我缺少什么?预先感谢您的帮助。

ire*_*ene 5

模板无法读取模型CompanyProfile。在获取任何属性之前,您必须先创建模型的实例。

假设您有以下几个实例CompanyProfile

CompanyProfile.objects.get(pk=1) --> 这有一个company_name“Adidas” CompanyProfile.objects.get(pk=2) --> 这有一个company_name“Nike”

假设您想展示 Nike 和 Adidas。

那么您可以这样做:

class CompanyProfile(models.Model):
   company_name = models.CharField(max_length=25)

class CompanyProfileView(views.TemplateView):
   template_name = 'my_template.html'

   def get_context_data(self, **kwargs):
       context = super(CompanyProfileView, self).get_context_data(**kwargs)
       # here's the difference:
       context['company_profiles'] = CompanyProfile.objects.all()
       return context
Run Code Online (Sandbox Code Playgroud)

然后,像这样渲染你的模板:

{% for company in company_profiles %}
    {{ company.company_name }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!