Django form with a list of objects

I have a problem with returning an object from a django form after submitting.

I have a list of objects (populated MyObject, not django model) populated by another python package.

In models.pyI have:

class MyObjectForm(forms.Form):

    def __init__(self, *args, **kwargs):
        # Get the list
        myobjects = kwargs.pop('myobjects')
        super(MyObjectForm, self).__init__(*args, **kwargs)
        choices = [(o, o.name) for o in myobjects]
        self.fields["my_objects"] = forms.TypedChoiceField(choices=choices)

For information, HTML looks fine.

In views.py, form.is_valid()always Falsewhen I press the submit button. Is there a problem?

When I change models.py to:

self.fields["my_objects"] = forms.TypedChoiceField(choices=choices, required=False)

In views.py, form.is_valid()there is True, but I can not get his objet object MyObject(I get an empty value). Is it possible? And if so, how can I do this?

+4
source share
1 answer

, ... MyObject , ? MyObject HTML, POST?

MyObject, ,

choices = [(o.some_stable_and_unique_id, o.name) for o in myobjects]

, ... TypedChoiceField "id" ..

+3

All Articles