I have a model that looks like ...

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()

    def __unicode__(self):
        return u'%s %s' % (self.name, self.birthday)

class Address(models.Model):
    person = models.ForeignKey(Person)
    address = models.CharField(max_length=150)

    def __unicode__(self):
        return u'%s %s' % (self.person, self.address)

class Anniversy(models.Model):
    person = models.ForeignKey(Person)
    anniversy = models.DateField()

    def __unicode__(self):
        return u'%s %s' % (self.person, self.anniversy)

If I want to print out all of the fields into an HTML table what would be the easiest way. I was thinking off getting all of the fields returned into a single list and then just enumerate through them ?

Thanks,

I'm not quite sure what you mean, but you can access Person's properties using a template. If you have a list of Person's passed to the template (lets call it persons_list), then you could do something like this in Django Template Language:

<table>
    {% for person in persons_list %}
        <tr>
            <td>{{ person.name}}</td>
            <td>{{ person.birthday }}</td>
            <td>{{ person.anniversary }}</td>
            <td>{{ person.address }}</td>
        </tr>
    {% endfor %}
</table>

This is just a basic idea. I prefer this way because any changes I need to make are right there in the template, and nothing is hard-coded into the view or template tags. Obviously you could play with the layout and make it how you want. You said something about a list, the only thing I could think of right now is to add a helper function with Template Tags. A template tag like this might be what you are talking about:

def person_info_list(person_obj):
    return [person_obj.name, person_obj.birthday, person_obj.anniversary, person_obj.address]

Then the template could be changed to:

{% load my_cool_tags %}
<table>
    {% for person in persons_list %}
        <tr>
            {% for info_item in person|person_info_list %}
                <td>{{ info_item }}</td>
            {% endfor %}
        </tr>
    {% endfor %}
</table>

Just an idea.. Honestly I would probably do the first one. It seems like it would be easier to make future changes, instead of hard-coding a certain list order to make the page look right. I guess I'm saying I would let the view control the view, and not the model or controller. You said something about iterating a list of values so I threw it in there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.