SeanVDH
SeanVDH

Reputation: 916

Django Template only Accesses One Value from the Model

I have a variety of classes, two of which have a structure as such:

class SomeClass(models.Model):
    name = models.CharField(max_length=60, db_index = True, blank=True)
    value = models.CharField(max_length=60, db_index = True, blank=True)
    year = models.DateField(db_index = True, blank=True)
    tags = models.ManyToManyField(Tag, blank=True)

    def __unicode__(self):
        return self.name

        class Meta:
            ordering = ('name',)

The view is as follows:

def home_page(request):
    classList = SomeClass.objects.values('name')
    someInstance = classList[0]
    return render_to_response("base.html", {"classList":classList, "someInstance":someInstance})

The template:

<!DOCTYPE html>

<html>
    <head>
    {% load staticfiles %}
    <title> Title </title>
            <link rel="stylesheet" type="text/css" href="{% static "styles/base.css" %}" />
</head>

<body>
    <div id="banner">
        BANNER TEXT
    </div>
    <div id="banner-wrapper">
    </div>  
    <div id="sidebar">
        CLASS
        <ul>
            {% for someClass in classList %}
            <li><a href="/CLP/{{class.name}}">{{class.name}}</a></li>
            {% endfor %}
        </ul>
        </div>

    <div id="someClass">
        {% block class %}

        <h2> {{someInstance.name}} </h2>
        <br>
        <h4> {{someInstance.value}} </h4> 

        {% endblock class %}
    </div>
</body>

In my template, I can readily access {{ someInstance.name }} for either, but I do not get values for if I try {{ someInstance.value }} or the like. I have verified that the values exist, and that the models are populated using the django admin page, as well as the shell. What else can I try?

I am on using django 1.6

Upvotes: 0

Views: 27

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174662

You are only fetching the name property in your view:

def home_page(request):
    classList = SomeClass.objects.values('name')
    ------------------------------^^^^^^^^^^^^^^

This is why the other properties of your object are not available in your template.

Also, your template - not sure if its a copy paste problem:

{% for someClass in classList %}
    <li><a href="/CLP/{{class.name}}">{{class.name}}</a></li>
{% endfor %}

Here I believe you need {{ someClass.name }}

Also, you have an indentation issue in your models:

def __unicode__(self):
    return self.name

    class Meta:
        ordering = ('name',)

The class Meta: should be at the same level as the def, and __unicode__ should return a unicode object:

def __unicode__(self):
    return unicode(self.name)

Upvotes: 1

Related Questions