I made a simple django form, with a list of choices (in radio buttons):
class MyForm(forms.Form):
choices=forms.ChoiceField( widget=forms.RadioSelect(), choices=[(k,k) for k in ['one','two','three']],label="choose one")
I would like the form to submit automatically when a user selects one of the options. In straightforward HTML I would've done it as
<select name='myselect' onChange="FORM_NAME.submit();">
....
</select>
But I do not know how to integrate this into the form class without writing a template. Specifically, I would need to know FORM_NAME
so I can call FORM_NAME.submit()
in the above snippet.
Can it be done without using a template?
One can create forms in Django and use them to fetch data from the user in a convenient manner. To begin with forms, one needs to be familiar about GET and POST requests in forms. GET : GET, by contrast, bundles the submitted data into a string, and uses this to compose a URL.
Django’s login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET, by contrast, bundles the submitted data into a string, and uses this to compose a URL.
POST: Any request that could be used to change the state of the system – for example, a request that makes changes in the database – should use POST. Illustration of Django Forms using an Example.
As discussed in the Django form handling process above, the view has to render the default form when it is first called and then either re-render it with error messages if the data is invalid, or process the data and redirect to a new page if the data is valid.
I think you do not need to know the form name. This should work as well:
<select name='myselect' onChange="this.form.submit();">
A quick solution to integrate this into your form would involve adding a attribute to your widget.
widget=forms.RadioSelect(attrs={'onchange': 'this.form.submit();'})
Now one could argue if this isn't better separated from your form definition (separating definition, style and behaviour), but that should do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With