TypeError对象不可迭代

时间:2013-08-29 13:34:28

标签: django python-2.7 django-templates detailview

尝试在Django模板中循环变量时出现以下错误。有问题的变量是我的DetailView子类中指定的模型的相关对象:

  

/ en / applicants / 50771459778 /

中的TypeError      

'Householdmember'对象不可迭代

这是我的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>

被注释掉的部分(即<!-- -->标签之间的部分)起作用,这使我认为我应该能够遍历householdmember变量。但是当我尝试这样做时,它不起作用 - 我只是得到了上面的TypeError。

我已经搜索了stackoverflow.com以获得答案,但我能找到的最接近的答案是:django how to loop through the context object passed back by a generic detailview?,但它并没有解决我的问题,我想是因为我使用的是基于类的视图。

非常感谢任何帮助。谢谢!

3 个答案:

答案 0 :(得分:3)

你无法理解模型实例。 我建议您使用评论代码。

如果您仍想使用forloop,也许可以添加以下代码:

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 ] 

答案 1 :(得分:0)

我设法解决了这个问题;这是怎么回事。我使用了这里的信息:Iterate over model instance field names and values in template

以下是我添加到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>

这会得到所需的输出。

答案 2 :(得分: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 %}