Accessing MultipleChoiceField choices values

Accessing MultipleChoiceField choices values

回眸一笑 发布于 2021-11-24 字数 1313 浏览 770 回复 2 原文

How do I get the choices field values and not the key from the form?

I have a form where I let the user select some user's emails for a company.
For example I have a form like this (this reason for model form is that it's inside a formset - but that is not important for now):

class Contacts(forms.ModelForm):
   def __init__(self, *args, **kwargs):
        super(Contacts, self).__init__(*args, **kwargs)
        self.company = kwargs['initial']['company']
        self.fields['emails'].choices = self.company.emails
        # This produces stuff like:
        # [(1, 'email@email.com'), ...]

   emails = forms.MultipleChoiceField(required=False)

    class Meta:
        model = Company

and I want to get the list of all selected emails in the view, something like this:

  form = ContactsForm(request.POST)
  if form.is_valid():
       form.cleaned_data['emails'][0] # produces 1 and not email

There is no get_emails_display() kind of method, like in the model for example. Also, a suggestion form.fields['emails'].choices does not work, as it gives ALL the choices, whereas I need something like form.fields['emails'].selected_choices?

Any ideas, or let me know if it's unclear.

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仅此而已 2022-06-07 2 楼

It might not be a beautiful solution, but I would imagine that the display names are all still available from form.fields['emails'].choices so you can loop through form.cleaned_data['emails'] and get the choice name from the field's choices.

苏辞 2022-06-07 1 楼

Ok, hopefully this is closer to what you wanted.

emails = filter(lambda t: t[0] in form.cleaned_data['emails'], form.fields['emails'].choices)

That should give you the list of selected choices that you want.