Skip to content Skip to sidebar Skip to footer

How To Put Data From Manytomanyfield To Choices In Multiplechoicefield

I have a form: *# dialogues.forms* class CreateConferenceForm(forms.Form): ... participants = forms.MultipleChoiceField(choices=?) ... And I need to put in choices ar

Solution 1:

If you're creating an instance of a conference model with your form, you should consider using Django's ModelForm, which is designed to be used in the creation and editing of model instances.

In either case, you can use a ModelMultipleChoiceField to serve your purpose, which is simply a MultipleChoiceField backed by a queryset for its choices. You can use this field in either a standard Form or a ModelForm.

To customize the choices based on the request, you can set the queryset in your view.

For example:

forms.py

classCreateConferenceForm(forms.Form):
    # An initial queryset is required, thisis overwritten in the view
    participants = forms.ModelMultipleChoiceField(Person.objects.all())

views.py

def new_conference(request):
    data = request.POST if request.method == 'POST'else None

    conference_form = CreateConferenceForm(data=data)
    conference_form.fields['participants'].queryset = my_person.friends.all()

    ifdata:
        if conference_form.is_valid():
            # etc

    return render...

Note that it is important for you to set the queryset prior to calling is_valid on the form, since the queryset is used in validation, and prior to sending passing the form to a template, since the queryset is used to generate the choices shown.

Solution 2:

You can try this

classCreateConferenceForm(forms.Form):
    """
    """
    participants = forms.MultipleChoiceField()

    def__init__(self, *args, **kwargs):
        # Pass the request in the form.
        self.request = kwargs.pop('request', None) 

        super(CreateConferenceForm, self).__init__(*args, **kwargs)

        if self.request:
            pass# Get the person object according to you need. Whether from request or hard-coded.
        person = Person.objects.filter().first()
        friend_choices = [(dct['id'], dct['id']) for dct in (person.friends.values('id'))]
        self.fields['participants'].choices = friend_choices

As friend field objects are also Person as MamyToMany with self. you can try this also

classCreateConferenceForm(forms.Form):
    """
    """# Replace second 'id' in values_list('id', 'id') with the field in you person model.
    participants = forms.MultipleChoiceField(choices=list(Person.objects.filter().values_list('id', 'id')))

Post a Comment for "How To Put Data From Manytomanyfield To Choices In Multiplechoicefield"