Reputation: 1496
I have a general question to the django-admin.
Is it possible to react on form changes?
I have a select field in my django-admin detail site. Whenever I change the data from the select field, I want to change fields which are read-only.
Has anybody ever dealt with this issue?
Upvotes: 5
Views: 4545
Reputation: 4460
Found a great answer by Abhijith K in another SO Q&A:
How can i add a onchange js event to Select widget in Django?
reciept=forms.ChoiceField(reciept_types, widget = forms.Select(attrs = {'onchange': "myFunction();"}))
To be clear, this is what you add within your widget definition: attrs = {'onchange': "myFunction();"}
to define which JS function will be called, in this when an onchange
event is triggers.
In the ModelAdmin you can then define a JavaScript file that you want to have access to, where you can define your function "myFunction()":
@admin.register(AnswerTree)
class AnswerTreeAdmin(ModelAdmin):
form = AnswerTreeForm
...
class Media:
js = ("admin_js/answertree_modeladmin.js",)
Django docs on defining assets (Like JavaScript & CSS) on your ModelAdmin: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-asset-definitions
What is also useful, I found out that you can access the value of the input by using attrs = {'onchange': "myFunction(this.value);"}
, note that I am passing the argument this.value
here now.
Example of the JavaScript function definition:
myFunction = (value) => {
console.log(value)
}
OR
myFunction(value) {
console.log(value)
}
Upvotes: 1
Reputation: 1868
My two cents:
As any other guys said it is a javascript
work. In admin pages Django pases jquery
. It is called django.jQuery
. So basilly you would do what @Ashfaq suggested. You will create a custom_script.js
and added to the Media
metaclass.
Basically(as @Ashfaq):
class MyModelAdmin(admin.ModelAdmin):
class Media:
js = ("js/custom_script.js",)
and custom_script.js
will be something like this(assuming that your select
field is called id_category
):
django.jQuery( document ).ready(function() {
console.log( "ready!" );
django.jQuery('#id_category').change(function() {
alert( "Handler for #id_category was called." );
});
});
The ready
function will guarantee the handler is getting set.
Upvotes: 4
Reputation: 1891
I think the thing that will work here is to add jQuery + your custom javascript and play with the events / clicks what-ever you want with elements.
class MyModelAdmin(admin.ModelAdmin):
class Media:
js = ("js/custom_script.js",)
in custom_script you can add click or change events as you want.
Upvotes: 2