2017-02-09 81 views
0

我只是在學習CBV,並且在將對象傳遞給TemplateView時遇到困難。這已經非常令人沮喪,因爲我知道這應該是非常基本的。如何將對象傳遞給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

你做錯了什麼事情很少,但爲了幫助你,我們需要知道你究竟想要達到什麼目的? –

回答

1

模板不能讀取模型CompanyProfile。在獲取任何屬性之前,您必須首先創建模型的實例。

假設有的CompanyProfile的幾個實例:

CompanyProfile.objects.get(PK = 1) - >此具有company_name = 「阿迪達斯」 CompanyProfile.objects.get(PK = 2) - - >這有一個company_name =「耐克」

而假設你想展示耐克和阿迪達斯。

然後這裏是你如何能做到這一點:

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 %} 

我希望幫助!

+0

它的工作!這真的很有幫助。上下文位讓我困惑,但我現在得到你的幫助。謝謝。 – Dan

+0

很高興知道! :) – irene