Gustavo Sooeiro
Gustavo Sooeiro

Reputation: 327

django admin - How to add javascript at the end of a file

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.

Upvotes: 5

Views: 5432

Answers (4)

Darwin
Darwin

Reputation: 2037

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 %}

Upvotes: 0

Bruno Wego
Bruno Wego

Reputation: 2430

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

Upvotes: 3

mrash
mrash

Reputation: 903

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

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

Upvotes: 2

Sam Creamer
Sam Creamer

Reputation: 5361

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!

Upvotes: 3

Related Questions