Automaticall list all fields of generic model in template

55 views
Skip to first unread message

bovender

unread,
Oct 16, 2011, 3:24:13 AM10/16/11
to django...@googlegroups.com
Hi all,

new to Django and loving it.

Is there a way to automatically generate HTML output for the fields of a model instance?

I'm looking for something similar to form.as_table, just without the form widgets.

Currently I find myself manually repeating all the typing work for the detail view templates that I already did for the model definitions.

Thanks

bovender

Mario Gudelj

unread,
Oct 16, 2011, 5:57:56 PM10/16/11
to django...@googlegroups.com
I think you need this https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/iGP654BL2HMJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Andre Terra

unread,
Oct 17, 2011, 9:43:32 AM10/17/11
to django...@googlegroups.com
Even better, use django-form-utils!

https://bitbucket.org/carljm/django-form-utils/overview


Cheers,
AT

Tom Evans

unread,
Oct 17, 2011, 11:32:47 AM10/17/11
to django...@googlegroups.com
Did either of you read the OPs email? He is not looking for forms...

OP:

There is nothing built in, but you can easily iterate through a
model's fields, they are all available in the _meta attribute on a
model instance:

>>> u = User.objects.get(id=1)
>>> for field in u._meta.fields:
... print "%s => %s" % (field.name, getattr(u, field.name))
...
id => 1
username => tevans@...
first_name => Tom
last_name => Evans
email => tevans@...
is_staff => True
is_active => True
is_superuser => True
last_login => 2011-10-17 15:46:33
date_joined => 2008-11-10 10:54:33

Using this information, you can easily produce a method that will
output a HTML table of that data. If you can modify your model
classes, you can make them inherit from an abstract base model that
includes this method, and then it will be available in all your
classes (that inherit from the base class, obviously).

Much more hackily, you could monkey patch models.Model instead.

Cheers

Tom

Reply all
Reply to author
Forward
0 new messages