I think I've read most of the "related/duplicate" questions around (i.e. verbose from template-tag, iterate over field names, iterate through models, and a few, more ...)
Unfortunately I'm afraid I need some hand holding ... as I'm a django n00b and can't seem to make it work. Here is the result I want in the html:
<!-- this in some section of the template -->
First Name : . Joe
Last Name : .. Blogs
<!-- this in another section -->
City: ....... Xanadu
Country: ..... Mongolia
Occupation: .. Programmer
<!-- this in another section of the template -->
Age: ......... 75
Height: ...... 180 cm
Eye color: .. red
With 4 or 5 sections and 10 possible fields each I don't want to just do
{% if data.first_name %}
First Name: {{ data.first_name }}
{% endif %}
fourty times! :-/ ... so here's (roughly) my attempt:
model.py
class GenericPerson(models.Model):
first_name = models.CharField(_('First Name'),
max_length = 200,
help_text = _('What is your name?'))
last_name = models.CharField(_('Last Name'),
max_length = 200,
help_text = _('What is your name?'))
etc, etc ...
class Meta:
abstract = True
class Person(GenericPerson):
age_in_years = models.PositiveIntegerField(_('Age'),
null = True,
blank = True,
help_text=_('When was you born?, mate'))
location = models.ForeignKey(GeographicalProfile,
verbose_name=_('geolocations'),
null = True,
blank = True)
height = ... etc, etc.
views.py
...
try:
person = Person.objects.filter(pk=product_id)
except Person.DoesNotExist:
raise Http404
generaldata = person.values('first_name',
'last_name',
etc, etc,
)[0]
localdata = person.values('city',
'country',
etc, etc
)[0]
physicaldata = person.values('age',
'height',
'eye_color',
etc, etc
)[0]
extra_context[data] = generaldata
extra_context[loc] = localdata
extra_context[phys] = physicaldata
return render_to_response(template_name, extra_context ,context_instance=RequestContext(request))
using that view, I can
template.html
{% for p in phys.items %}
<ul>
{% if p.1 %}
<li>{{p.0}} : {{p.1}}</li>
{% endif %}
</ul>
{% endfor %}
for the different sections. But this will return the field as age_in_years, eye_color (instead of the name). Ok, so from the posts above I create a custom template-tag,
from django import template
register = template.Library()
@register.filter
def get_name(object):
return object._meta.verbose_name # put here whatever you would like to return
register.tag('get_name', get_name)
, load it in the template {% load person_extras %}, now ... I've tried blindly to use this {{something|get_object_name}} everywhere in the template ... but my brute force without understanding gives me:
'str' object has no attribute '_meta'
'list' object has no attribute '_meta'
'tuple' object has no attribute '_meta'
'dict' object has no attribute '_meta'
'ValuesQuerySet' object has no attribute '_meta'
So, where do I use this template tag? or how do I modify my view to make use of this template tag in the for-loop?
Thank you for the insight