我只是在学习CBV,并且很难将对象传递给TemplateView。这非常令人沮丧,因为我知道这应该是非常基本的。
这是我的views.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()
这是我的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
这是urls.py
urlpatterns = [
url(r'^accounts/companyprofile/$', CompanyProfileView.as_view()),
]
最后,这是模板:
{% extends '_layouts/base.html' %}
{% block title %}Company Profile{% endblock %}
{% block headline %}<h1>Company Profile</h1>{% endblock %}
{% block content %}{{ CompanyProfile.company_name }}{% endblock %}
我错过了什么?提前感谢您的帮助。
答案 0 :(得分:2)
模板无法读取模型CompanyProfile
。在获得任何属性之前,必须先创建模型的实例。
假设您有CompanyProfile
的几个实例:
CompanyProfile.objects.get(pk = 1) - &gt;这有一个company_name
=&#34;阿迪达斯&#34;
CompanyProfile.objects.get(pk = 2) - &gt;这有一个company_name
=&#34; Nike&#34;
假设你要展示耐克和阿迪达斯。
然后,您可以这样做:
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
然后,渲染你的模板:
{% for company in company_profiles %}
{{ company.company_name }}
{% endfor %}
我希望有所帮助!