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

大城市里の小女人 提交于 2019-12-13 05:19:24

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/7978107/django-forms-how-to-iterate-over-a-choices-of-a-field-in-django-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!