4

I have a problem to get back an object from a django form after submission.

I have an object list (filled with MyObject, not a django model) filled by another python package.

In models.py, I 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, the HTML looks OK.

In views.py, form.is_valid() is always False when I click on the submit button. Is there a problem ?

When I change models.py with :

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

In views.py, form.is_valid() is True but I can't get back my objet MyObject (I get an empty value). Is that possible ? And if yes, how can I do that ?

1 Answer 1

3

Look at what you used as choices... MyObject instances, really ? How is a MyObject instance supposed to be sent to a browser as part of a HTML form and then back to your server thru a POST request body ?

If you have some persistant unique identifier for each of your MyObject instances, use this for your choices, ie

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

Note that it won't solve all of your issues... You'll then have to subclass TypedChoiceField to retrieve the object based on its "id" etc.

Sign up to request clarification or add additional context in comments.

1 Comment

MyObject is an oject with some properties created by another package (which not intended to be save in database). I thought it was impossible... I don't have a unique identifier but I can create one and a dictionary in views.py before passing the list in form constructor and retrieve the selected object after form validation with this custom ID. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.