TypeError对象不可迭代

12

当我尝试在Django模板中遍历变量时,出现了以下错误。所涉及的变量是我在DetailView子类中指定的模型的相关对象:

TypeError at /en/applicants/50771459778/

'Householdmember' object is not iterable

这是我的models.py文件:

class Applicant(models.Model):
    user              = models.ForeignKey(User, editable=False)
    bank_card_number  = models.CharField(_('Bank card number'),max_length=50, unique=True)
    site_of_interview = models.IntegerField(_('Site of interview'), choices = SITE_CHOICES, default=TIRANA, blank=False)
    housenumber       = models.CharField(_('House Number'),max_length=8)
    address_line1     = models.CharField(_('Address line 1'),max_length=50)
    address_line2     = models.CharField(_('Apt #'),max_length=50,blank=True) 
    municipality      = models.CharField(_('Municipality/commune'),max_length=25)
    district          = models.CharField(_('District'),max_length=25,blank=True)
    urban             = models.IntegerField(_('Area (urban/rural)'), choices = AREA_CHOICES, blank=False)
    postal            = models.CharField(_('Postal code'),max_length=25,blank=True) 

class Householdmember(models.Model):
    applicant         = models.ForeignKey(Applicant)
    first_name        = models.CharField(_('First name'),max_length=50,blank=False)
    middle_name       = models.CharField(_('Middle name'),max_length=50,blank=True) 
    last_name         = models.CharField(_('Last name'),max_length=50,blank=False)
    national_id       = models.CharField(_('National ID'),max_length=50,blank=False, unique=True)
    male              = models.IntegerField(_('Gender'), choices = GENDER_CHOICES, blank=False)
    date_of_birth     = models.DateField()
    rel_to_head       = models.IntegerField(_('Gender'), choices = RELTOHEAD_CHOICES, blank=False)
    disability        = models.IntegerField(_('Is disabled?'), choices = YESNO_CHOICES, blank=False)
    created_at        = models.DateTimeField(auto_now_add = True)
    updated_at        = models.DateTimeField(auto_now = True)

这是我的 urls.py 文件:

class ListViewApplicants(ListView):
    paginate_by = 100
    def get_queryset(self):
        return Applicant.objects.all()

class DetailViewUnmask(DetailView):
    def get_object(self):
        return self.get_queryset().get(pk=mask_toggle(self.kwargs.get("pk_masked")))

urlpatterns = patterns('',
    url(r'^$',
        login_required(ListViewApplicants.as_view( 
                            template_name='applicants/index.html',
                            #context_object_name='form',
                            )),
        name='index'),
    url(r'^(?P<pk_masked>\d+)/$',
        login_required(DetailViewUnmask.as_view( model=Applicant,
                            template_name='applicants/detail.html'
                            )), 
        name='detail'),

以下是我模板中相关的部分,detail.html

<h2>Household members</h2>
<table class="package_detail">
    <tr>
        {% include "applicants/householdmember_heading_snippet.html" %}
    </tr>
    
    {% for householdmember in applicant.householdmember_set.all %}
    <tr>
        
        {% for field in householdmember %}
            <td>{{ field }}</td>
        {% endfor %}
        <!--
        <td>{{ householdmember.first_name }}</td>
        <td>{{ householdmember.middle_name  }}</td>
        <td>{{ householdmember.last_name  }}</td>
        <td>{{ householdmember.national_id  }}</td>
        <td>{{ householdmember.get_male_display }}</td>
        <td>{{ householdmember.date_of_birth }}</td>
        <td>{{ householdmember.get_rel_to_head_display }}</td>
        <td>{{ householdmember.get_disability_display }}</td>
        -->
    </tr>
    {% endfor %}
</table>
3个回答

8

您不能对一个模型实例进行迭代。 我建议您使用您的已注释代码。

如果您仍然想要使用for循环,也许您可以添加这段代码:

class Householdmember(models.Model):
    # all yuur fields...

    def __iter__(self):
        return return [field.value_to_string(self) for field in Householdmember._meta.fields]

但是,没有人推荐这样做。

更好的方式是:

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 ] 

你好Lalo,感谢您的快速回复。有一个问题:在您上面的代码中,for field in Project._meta.fields中的Project是什么? - Shafique Jamal
抱歉,应该是Householdmember。 - Leandro

0

我成功解决了这个问题,以下是我的解决方法。我使用了这里的信息:在模板中迭代模型实例字段名称和值

以下是我添加到models.py文件中的内容:

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

这是我的detail.html文件最终的样子:

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

这将会得到所期望的输出。


0
如果你的views.py文件像我的一样:
    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)

你可以通过在模板文件中打印{{titles}}来打印所需的值。

    % extends "main/header.html" %}
    {% block title %} 
        {{titles}}
    {% endblock %}
    {% block content %} 
        {{titles}}
    {% endblock %}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接