Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Reuse the Django admin's javascript (example with prepopulated_fields.js)
<script src="{% static "admin/js/jquery.js" %}"></script>
<script src="{% static "admin/js/jquery.init.js" %}"></script>
<script src="{% static "admin/js/urlify.js" %}"></script>
<script src="{% static "admin/js/prepopulate.js" %}"></script>
<script>
// adaptation from django/contrib/admin/templates/admin/prepopulated_fields_js.html
(function($) {
var field = {
id: '#{{ form.###DESTINATION FIELD NAME###.auto_id }}',
dependency_ids: ['#{{ form.###SOURCE FIELD NAME###.auto_id }}'],
dependency_list: ['{{ form.###SOURCE FIELD NAME###.name }}'],
maxLength: {{ form.###DESTINATION FIELD NAME###.field.max_length|default_if_none:"50"|unlocalize }}
};
$('.field-{{ form.###DESTINATION FIELD NAME###.name }}').addClass('prepopulated_field');
$(field.id).data('dependency_list', field['dependency_list'])
.prepopulate(field['dependency_ids'], field.maxLength);
})(django.jQuery);
</script>
@romain-dartigues
Copy link

romain-dartigues commented Apr 10, 2021

Hi nine years ago! Thank you for the hint.
As of today in Django 3.2 the solution would be:

<script src="{% static "admin/js/vendor/jquery/jquery.min.js" %}"></script>

We do not need the (function($) { ... })(django.jQuery); except if jquery.init.js is included and we specifically want to ensure we get the same version as Django (i.e.: another jQuery version might be included in the page) or, as in your example, we want to load some Django jQuery extensions.

@mohitbestpeers
Copy link

mohitbestpeers commented Jun 27, 2022

@romain-dartigues , I am also facing the similar problem after upgrading to django 3.2, my admin pagination is not working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment