Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - post form on select

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?

like image 299
olamundo Avatar asked Feb 08 '11 15:02

olamundo


People also ask

How do I create a form in Django?

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.

What is the difference between get and post methods in Django?

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.

When should I use POST request in Django?

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.

How to handle invalid data in a form in Django?

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.


1 Answers

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.

like image 163
Reiner Gerecke Avatar answered Sep 26 '22 07:09

Reiner Gerecke