5

I am trying to add a custom javascript file to a Django admin model page. I am using a class Media in the ModelAdmin, but the file is been loaded in the head section. I need at the end of the file. Does anyone knows how to do that?

Thank you all!

class Media:
        js = (
            'js/jquery.mask.min.js',
            'js/mask.js',       
        )

The aim of these scripts is to have masks working for some fields in the form.

4 Answers 4

3

You can extend the template files of the admin section and put them in there directly. See https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#overriding-admin-templates

I have done it in some of my own projects. For example, in your templates folder, you can have:

/templates/admin/base_site.html

In that file you can make whatever changes you want (same as regular Django templates). In your case, it would probably be something like this:

{% extends 'admin/base_site.html' %}
{% load static %}  
{% block footer %}
<div id="footer"></div>
<script src="whatever/source/jquery.js" />
<script src="whatever/source/mask.js" />
{% endblock %}

Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! Your tip with @mrash's tip made the deal.
Glad to hear that! Good luck
3

Use window.addEventListener:

window.addEventListener('load', function() {
    (function ($) {
        // Code
    })(django.jQuery);
});

Another way:

window.onload = function () {
  if (typeof (django) !== 'undefined' && typeof (django.jQuery) !== 'undefined') {
    (function ($) {
      // Code
    }(django.jQuery));
  }
};

1 Comment

I think this is the better approach to avoid making an entire template just to add minimal JS on the admin site also it leverages the jQuery already present on the admin site.
2

in javascript code, you should force code to run after page load. for example in jQuery:

$(function(){
    /* this code runs after page load */
});

1 Comment

Thank you very much! Your tip with @Sam's tip made the deal.
0

base on the @sam-creamer answer, I changed the script tag:

{% extends 'admin/base_site.html' %}
{% load static %}  
{% block footer %}
<script src="{%static '/whatever/source/jquery.js' %}"></script>
<script src="{%static '/whatever/source/mask.js' %}"></script>
{% endblock %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.