0

I am totally new to jQuery. I spent quite a bit of time researching how to get jQuery to work in the Django Admin, specifically using the change_form.html.

In the {% block extrahead %} in the change_form.html template I eventually found out that I should write:

<script type="text/javascript">
(function($){
    $(function(){
        $("#id_fs1").attr("style", "width:10px");
    });

})(django.jQuery);
<script>

It worked like a charm but in the end it looks quite convoluted compared to:

<script type="text/javascript">
    document.getElementById("id_fs1").style.width = "50px";
</script>

(the above was placed in the {% block after_field_sets %})

My question is... Is there a more elegant way of using jQuery within the Django admin?

1 Answer 1

1

this should works as well:

<script type="text/javascript">
(function($){
        $("#id_fs1").width("10px");
})(django.jQuery);
<script>

First steps with jQuery are not easy, but you will find strength of jQuery over time .)

Also using jQuery in django admin is a step more difficult because of namespacing jQuery to not collide with potential another instance of jQuery (that (django.jQuery) on end of script, usually it's not required)

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

3 Comments

Thanks, that worked too. Am I right that the script does not wait for the DOM to be ready? It seems to only work in the after_field_sets block.
AFAIK it waits for domready event, this is only shorter way how to write it. See api.jquery.com/ready - there are more ways how to bind script with ondomready event in jQuery
Thank you I will go and check it out.

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.