8👍
✅
You can’t iter over a model instance.
I recommend you use your commented code.
If you still want to use a forloop, maybe you can add this code:
class Householdmember(models.Model):
# all yuur fields...
def __iter__(self):
return return [field.value_to_string(self) for field in Householdmember._meta.fields]
But, no one recommend that
That’s better:
class Householdmember(models.Model):
# all yuur fields...
def __iter__(self):
return [ self.first_name,
self.middle_name,
self.last_name,
self.national_id,
self.get_male_display,
self.date_of_birth,
self.get_rel_to_head_display,
self.get_disability_display ]
0👍
I managed to solve this; here is how. I used info from here: Iterate over model instance field names and values in template
Here is what I added to my models.py
file:
def get_all_fields(self):
fields = []
for f in self._meta.fields:
fname = f.name
# resolve picklists/choices, with get_xyz_display() function
get_choice = 'get_'+fname+'_display'
if hasattr( self, get_choice):
value = getattr( self, get_choice)()
else:
try :
value = getattr(self, fname)
except User.DoesNotExist:
value = None
# only display fields with values and skip some fields entirely
if f.editable and f.name not in ('id', 'created_at', 'updated_at', 'applicant'):
fields.append(
{
'label':f.verbose_name,
'name':f.name,
'value':value,
}
)
return fields
And here is what my detail.html
file ended up looking like:
<table class="package_detail">
<tr>
{% include "applicants/householdmember_heading_snippet.html" %}
</tr>
{% for householdmember in applicant.householdmember_set.all %}
<tr>
{% for field in householdmember.get_all_fields %}
<td>{{ field.value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
And this gives the desired output.
- Django and reverse relations from foreign keys
- How to find top-X highest values in column using Django Queryset without cutting off ties at the bottom?
- Django run tasks (possibly) in the far future
- Django: vps or shared hosting?
- Using Django auth User model as a Foreignkey and reverse relations
0👍
If your views.py file is something like mine :
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.forms import UserCreationForm
from .models import Home
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.db.models import Count
# Create your views here.
def homepage(request):
context = RequestContext(request)
titles_string = Home.objects.get(id=2)
print (titles_string)
context_dict = {'titles' : (titles_string)}
print(context_dict)
return render_to_response('main/home.html', context_dict, context)
you can print the required value by printing in the template file :{{titles}}
% extends "main/header.html" %}
{% block title %}
{{titles}}
{% endblock %}
{% block content %}
{{titles}}
{% endblock %}
Source:stackexchange.com