4

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

Manuel Santi
  • 1,106
  • 17
  • 46

2 Answers2

8

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
Toan Quoc Ho
  • 3,266
  • 1
  • 14
  • 22
  • @abnerh69, I didn't get your idea. Why it should be "class Media"? The reason why I use `class Meta` because that's a feature in Django which allows us to set metadata for other classes – Toan Quoc Ho Feb 15 '20 at 06:54
  • 1
    It's because Django (versions 1.8 to 3.0) documentation at https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#modeladmin-asset-definitions. But your answer helps me a lot. Just change Meta for Media. – abnerh69 Feb 15 '20 at 17:09
3

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();'})
        }