Django -- Form Field on change

django, python

Solution

It looks like you are using Django Crispy forms and not plain Django forms.

If you want to set the `onchange` attribute, you should be able to just pass that as a keyword argument, as described in the docs.

Field('account_type',
      placeholder="Account Type",
      css_class='form-control',
      onchange="myChangeHander()"
)

A better way would be to give that element an id and to attach an event in JavaScript.

Field('account_type',
      placeholder="Account Type",
      css_class='form-control',
      css_id="account_type_id"
)

Assuming you use jQuery, you would put something like this somewhere in a `<script>` tag or JavaScript file:

$("#account_type_id").on("change", function() {...});      

Problem

I'm using Django forms to display data. There is a HTML select field - which has 2 options a) teachers and b) Students. Django forms:- ``` self.fields['account_type'].choices = [('student','Student'),('teacher', 'Teacher')] self.helper.layout = Layout( HTML('''<h5>Sign Up Information</h5>'''), Div( Field('account_type', placeholder="Account Type", css_class='form-control'), css_class = 'form-group' ), ``` Based on whether you select "Student" or "Teacher" you need auto populate another field - topics. How can I fire the 'onchange' event in Django forms.

Original source