0

我正在将表单列表保存为要发送到模板的视图中的变量。

当我迭代模板中的表单列表时,它给了我错误

AttributeError:“长”对象没有属性“获取”

我最初尝试将表格保存在字典中,但遇到了同样的错误。我可以遍历传递给模板的查询集,但表单的列表或字典似乎无法被迭代。

有什么解决办法吗?

这是我的相关代码:

表格.py

from django.contrib.auth.models import User
from django import forms
from apps.account.models import UserProfile

class StaffUserTypeForm(forms.Form):
    user_type = forms.ChoiceField(choices=UserProfile.STAFF_CHOICES)

帐户/models.py

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    DEFAULT = 0
    ADMIN = 1
    MANAGER = 2
    COORDINATOR = 3
    REALTOR = 4
    TEAM_CAPTAIN = 5
    PROPERTY_OWNER = 6
    PRELOAD = 7
    BILLING = 8
    COORDINATOR_PRELOAD = 9

    STAFF_CHOICES = (
        (ADMIN, 'Admin'),
        (MANAGER, 'Manager'),
        (COORDINATOR, 'Coordinator'),
        (COORDINATOR_PRELOAD, 'Coordinator +Preload'),
        (PRELOAD, 'Preloader'),
        (BILLING, 'Billing'),
    )
    ...

视图.py

from forms import *
    ...
    staff = Staff.objects.all()
    roles = []
    for member in staff:
        form = StaffUserTypeForm(initial=member.user.userprofile.user_type)
        roles.append(form)
    context.update({'staff':staff,'roles':roles})
    ...

模板(这是它打破的地方)

{% for role in roles %}
{{role}}
{% endfor %}

但这很好用:

{% for member in staff %}
{{member.user.first_name}}
{% endfor %}

更新

该特定错误是因为我没有initial在表单中指定 user_type。

应该:

form = StaffUserTypeForm(initial={'user_type':member.user.userprofile.user_type})

但是,我仍然有为每个员工吐出表格的问题,因为我无法在模板中将变量引用为字典键:

如果:

roles = {}
for member in staff:
  roles[member] = StaffUserTypeForm(initial={'user_type':member.user.userprofile.user_type})

我无法获得特定工作人员的表格:

{% for member in staff %}
{{roles.member}}
{% endfor %}

不起作用,并且不会引发错误。我认为,它只是看起来不存在的角色['member']。

4

1 回答 1

1

既然roles字典既包含成员(作为键)又包含表单(作为值),为什么还需要遍历staff呢?只需遍历roles.

{% for member, form in roles.items %}
    {{ member }} : {{ form }}
{% endfor %}
于 2013-02-14T21:02:16.867 回答