Skip to content

Instantly share code, notes, and snippets.

@magopian
Created November 15, 2012 11:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save magopian/4078269 to your computer and use it in GitHub Desktop.
Save magopian/4078269 to your computer and use it in GitHub Desktop.
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

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

@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