in my django project i would to clean a field value based on an event in another field on a django admin add/edit form. i insert in the admin/change_form.html my call to js :
{{ block.super }}
<script type="text/javascript" src="{% static 'js/admin.js' %}"></script>
{{ media }}
{% endblock %}
then my admin.js:
(function($) {
$(document).ready(function() {
$("select[name='main_id']").change(function() {
$("select['test_id']").val('');
});
});
})(django.jQuery);
but when i open my django-admin page in console i get:
Uncaught TypeError: $ is not a function
on the "$(document).ready(function() {" line.
Someone can help me with this error?
So many thanks in advance
Instead of adding second copy of jQuery just make sure your JS is executed after djagno.jQuery
is defined.
You can solve this issue by simply wrapping your JS in with an event listener that fires when the window
has loaded.
window.addEventListener("load", function() {
(function($) {
$("select[name='main_id']").change(function() {
$("select['test_id']").val('');
});
})(django.jQuery);
});
The "load"
event is fired when the window
, as you might have guessed, loads. window.addEventListener()
simply registers an event listener that executes the contents of the anonymous function when the event fires. This happens after all resources have loaded.
Because the window
"load"
event will fire after $(document).ready()
you don't need that anymore.
Use the class Media in your admin.py file like this:
class Media:
js = (
'//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js', # jquery
'js/admin.js', # project static folder
)
Let's try to insert jQuery script before?
{{ block.super }}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous" defer></script>
<script type="text/javascript" src="{% static 'js/admin.js' %}" defer></script>
{{ media }}
{% endblock %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With