1
votes

How would one go about returning more than one field from a Django model declaration?

For instance: I have defined:

class C_I(models.Model):
    c_id = models.CharField('c_id', max_length=12)
    name = models.CharField('name', max_length=100)
    def __str__(self):
        return '%s' % (self.name)

which I can use, when called in a views.py function to return

    {{ c_index }}

        {% for c in c_index %}

            <div class='c-index-item' c-id=''>

                <p>{{ c.name }}</p>

            </div>

        {% endfor %}

from a template. This is being called in my views.py like so:

c_index = C_I.objects.all()

t = get_template('index.html')

c  = Context({'c_index': c_index})

html = t.render(c)

How would I also include the c_id defined in the model above, so that I can include {{c.name}} and {{c.c_id}} in my template? When I remove the str method, I appear to get all of the results, however, it just returns blank entries in the template and will not let me reference the individual components of the object.

1
I have tried return '%s %s' % (self.name, self.c_id) and also return '%s, %s' % (self.name, self.c_id)BTC
You are passing a list of Calendar objects from the view function to the template to render, so for individual instances you should be able to access any attribute that the Calendar model defines (without defining a __str__ method). Try changing the content of the <p> tag to {{ c.c_id }}, {{ c.name }}. Does that result in any errors when you access the view?itsjeyd
It doesn't result in an error, but it is blank. Furthermore, when I print c_index, which is defined just as it is above, I only get the name and the c_id back, but if I comment out the str method, I get an array of calendar itemsBTC
What's your code for passing c_index to the template? I.e., can you please add the code of the view function responsible for rendering the template to your post?itsjeyd
I've added it to the body of the questionBTC

1 Answers

1
votes

What you have is fine. Your template should be:

    {% for c in c_index %}
        <div class='c-index-item' c-id='{{ c.c_id }}'>
            <p>{{ c.name }}</p>
        </div>
    {% endfor %}