On Fri, Apr 12, 2013 at 11:57 PM, Nick D <dominguez.nicho...@gmail.com> wrote:
> Hi again!
>
> I'm looking to create a table based on a model. I'm trying to make it simple
> and reusable. I want to build the table headers (<th>) based on the fields
> in the model. Given a specific model, is there a way to dynamically build
> the headers in the template?
>
> Thanks!
>

I'd doubt it, using standard template tags. However, you can do
whatever you want in the view, or in a custom template tag, in order
to extract and return the field names in a list that you can iterate
over.

Whether the work is done in the view or in a template tag, the concept
is the same, examine either ModelClassName._meta.fields or
instance._meta.fields (they are equivalent), perhaps filtering it.
This will give you a list of fields to iterate over.

Presumably you will also want to output the values in the rows below
as well, in which case you simply iterate through the field names
again. You'll need another custom template tag to dynamically extract
a field from an instance based upon a template variable, fortunately
this is a much more common idiom, see this example:

http://djangosnippets.org/snippets/411/

Everything you wanted to know about custom template tags is here:

https://docs.djangoproject.com/en/1.5/howto/custom-template-tags/

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to