Skip to content Skip to sidebar Skip to footer

Typeerror Object Is Not Iterable

I am getting the following error when trying to loop over a variable in my Django templates. The variable in question is the related object of the model specified in my DetailView

Solution 1:

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:

classHouseholdmember(models.Model):# all yuur fields...def__iter__(self):
        returnreturn [field.value_to_string(self) for field in Householdmember._meta.fields]

But, no one recommend that

That's better:

classHouseholdmember(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 ] 

Solution 2:

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:

defget_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'ifhasattr( 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 entirelyif f.editable and f.name notin ('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:

<tableclass="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.

Solution 3:

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.defhomepage(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 %}

Post a Comment for "Typeerror Object Is Not Iterable"