Akamad007
Akamad007

Reputation: 1601

Django Forms: How to iterate over a Choices of a field in Django form

I dont know if I am doing this in the right manner.

I have a form:

class ConnectSelectMultipleForm(forms.Form):
    class Meta:
        model = Connect

    def __init__(self, *args, **kwargs):
        messages = kwargs.pop('messages')
        choices = []
        if messages:
            pass
        else:
            messages = []

        for message in messages:
            index = (message.id, {message.sender, message, message.id})
            choices.append(index)

        super(ConnectSelectMultipleForm, self).__init__(*args, **kwargs)
        self.fields['message'] = forms.MultipleChoiceField(choices=choices,
                                     widget=forms.CheckboxSelectMultiple)

As can be seen above i am sending {message.sender, message ,message.id} to the template. Now i want to access these variables in the template.

{% for field in select_form %}       
    {% for fi in field %}
        {{ fi.message }}
        {{ fi.message.sender }}
        {{ fi.message.id }}
    {% endfor %}
{% endfor %}

The above code is wrong. But can we do something similar to this? Or is there an alternative method to do what i am trying to do?

Thanks in advance.

###Edit

The ouput i am getting by just printing the field is as follows

 set([5, u'Everycrave', <Connect: The deal you refered has been bought>])

What i want is

Id : 5 ,Name : Everycrave , Content : The deal you refered has been bought

So I want those fields individually

Upvotes: 0

Views: 2544

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You don't want to "iterate over the field" at all. Django does this for you. The only issue you have is how to create the display value for the field's choices - for some reason, you're creating them as sets, when you just want a string. Your __init__ method should be something like this:

def __init__(self, *args, **kwargs):
    messages = kwargs.pop('messages', None)
    super(ConnectSelectMultipleForm, self).__init__(*args, **kwargs)
    if messages is None:
        messages = []

    choices = [(message.id, "%s: %s (%s)" % message.sender, message.text, message.id)
               for message in messages]

    self.fields['message'].choices = choices

Now you simply refer to the field in the template in the normal way: {{ form.message }}.

Upvotes: 4

Related Questions