Manuel Santi
Manuel Santi

Reputation: 1132

Django Admin intercept onchange event of a field and make an action

In my django project i would clear a field value every time another select field have an onChange event. I have an add form like thisone:

enter image description here

every time Template field change (onChange), Test Case field have to become blank.

How can i do this in a django admin add or edit page?

So many thanks in advance

Upvotes: 5

Views: 5295

Answers (2)

ZaherSarieddine
ZaherSarieddine

Reputation: 126

The event can also be set in the modelform meta widgets dict;

class ReceiptsForm(ModelForm):
    class Meta:
        model = Receipts
        fields = []
        widgets = {
            'partner_id': forms.Select(attrs={'onchange': 'this.form.submit();'})
        }

Upvotes: 4

Toan Quoc Ho
Toan Quoc Ho

Reputation: 3378

You could customize Admin asset definition and use JavaScript/jQuery to handle your problem. Here is an example:

admin.py

class TestCaseAdmin(admin.ModelAdmin):
    class Media:
        js = (
            'js/admin.js',   # inside app static folder
        )

admin.site.register(TestCase, TestCaseAdmin)

js/admin.js

if (!$) {
    // Need this line because Django also provided jQuery and namespaced as django.jQuery
    $ = django.jQuery;
}

$(document).ready(function() {
    $("select[name='template']").change(function() {
        $("select['test_case']").val('');
    });
});
  • template, test_case are field name on your model

Upvotes: 9

Related Questions