Dan
Dan

Reputation: 641

How to pass objects to a TemplateView?

I am just learning CBVs and having a tough time with passing an object to a TemplateView. This has been pretty demoralizing as I know this should be very basic.

Here is my 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()

And here is my 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

Here is urls.py

urlpatterns = [
    url(r'^accounts/companyprofile/$', CompanyProfileView.as_view()),
]

And finally, here is the template:

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

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

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

{% block content %}{{ CompanyProfile.company_name }}{% endblock %}

What am I missing? Thank you in advance for your help.

Upvotes: 1

Views: 3927

Answers (1)

irene
irene

Reputation: 2243

The template cannot read the model CompanyProfile. You have to create an instance of the model first before you get any attribute.

Suppose you have the several instances of CompanyProfile:

CompanyProfile.objects.get(pk=1) --> this has a company_name="Adidas" CompanyProfile.objects.get(pk=2) --> this has a company_name="Nike"

And suppose you want to display Nike and Adidas.

Then here's how you can do it:

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

Then, render your template like this:

{% for company in company_profiles %}
    {{ company.company_name }}
{% endfor %}

I hope that helps!

Upvotes: 5

Related Questions