Reputation: 12870
I am saving a list of forms as a variable in the view that I am sending to the template.
When I iterate the list of forms in the template, it gives me the error
AttributeError: 'long' object has no attribute 'get'
I've tried originally to save the forms in a dictionary, but got the same error. I can iterate through a queryset that I'm passing to the template, but the list, or dictionary, of forms cannot seem to be iterated.
Is there any solution for this?
Here's my relevant code:
forms.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)
account/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'),
)
...
views.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})
...
template (This is where it breaks)
{% for role in roles %}
{{role}}
{% endfor %}
But this works fine:
{% for member in staff %}
{{member.user.first_name}}
{% endfor %}
That particular error is because I didn't specify user_type in initial
for the form.
Should be:
form = StaffUserTypeForm(initial={'user_type':member.user.userprofile.user_type})
However, I still have the problem of spitting out the form for each staffmember, because I can't reference a variable as a dictionary key within the template:
if:
roles = {}
for member in staff:
roles[member] = StaffUserTypeForm(initial={'user_type':member.user.userprofile.user_type})
I can't get the form for the specific staffmember:
{% for member in staff %}
{{roles.member}}
{% endfor %}
Does not work, and does not throw an error. It just looks, I think, for roles['member'] which doesn't exist.
Upvotes: 0
Views: 2275
Reputation: 599796
Since the roles
dictionary contains both the members (as keys) and forms (as values), why do you need to iterate through staff
at all? Just iterate through roles
.
{% for member, form in roles.items %}
{{ member }} : {{ form }}
{% endfor %}
Upvotes: 1