[Solved]-TypeError object is not iterable


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.get_disability_display ] 


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)()
            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'):

    return fields

And here is what my detail.html file ended up looking like:

<table class="package_detail">
        {% include "applicants/householdmember_heading_snippet.html" %}
    {% for householdmember in applicant.householdmember_set.all %}
    {% for field in householdmember.get_all_fields %}
        <td>{{ field.value }}</td>
    {% endfor %}
    {% endfor %}

And this gives the desired output.


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)}

      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 %} 
    {% endblock %}
    {% block content %} 
    {% endblock %}

Leave a comment