Django -- Form Field on change
<p>I'm using Django forms to display data.</p>

<p>There is a HTML select field - which has 2 options a) teachers and b) Students.</p>

<p>Django forms:- </p>

<pre><code>self.fields['account_type'].choices = [('student','Student'),('teacher', 'Teacher')]

self.helper.layout = Layout(
                    HTML('''&lt;h5&gt;Sign Up Information&lt;/h5&gt;'''),
                    Div(
                        Field('account_type', placeholder="Account Type", css_class='form-control'),
                        css_class = 'form-group'
                    ),            
</code></pre>

<p>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.</p>

<p>It looks like you are using Django Crispy forms and not plain Django forms.</p>

<p>If you want to set the <code>onchange</code> attribute, you should be able to just pass that as a keyword argument, as <a href="https://django-crispy-forms.readthedocs.io/en/latest/layouts.html#layout-objects-attributes" rel="nofollow">described in the docs.</a></p>

<pre><code>Field('account_type',
      placeholder="Account Type",
      css_class='form-control',
      onchange="myChangeHander()"
)
</code></pre>

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

<pre><code>Field('account_type',
      placeholder="Account Type",
      css_class='form-control',
      css_id="account_type_id"
)
</code></pre>

<p>Assuming you use jQuery, you would put something like this somewhere in a <code>&lt;script&gt;</code> tag or JavaScript file:</p>

<pre><code>$("#account_type_id").on("change", function() {...});      
</code></pre>

python django