# importing jquery file in django template

**URL:** <https://forum.djangoproject.com/t/importing-jquery-file-in-django-template/13228>\
**Category:** Django Internals\
**Created:** [April 18, 2022, 9:10am UTC](https://forum.djangoproject.com/t/importing-jquery-file-in-django-template/13228 "2022-04-18T09:10:06Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![bibalani](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bibalani/32/8165_2.png) [@bibalani](https://forum.djangoproject.com/u/bibalani)\
**Post date:** [April 18, 2022, 9:10am UTC](https://forum.djangoproject.com/t/importing-jquery-file-in-django-template/13228/1 "2022-04-18T09:10:07Z")

</div>

Hi  
I am developing a warehouse management system using django. I much appreciate it if you help me fix the issue… In fact when I insert my jquery code in my html file all get and post request work well. But when I insert them into seperaed js file and tag it in my base.html and other template html file I face bellow error:

`Not Found: /regular_customer/{% url 'my_app:get_form_info' %}`

regular\_customer.js

 ![pic2](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/2X/3/38c69a349672d4a598dfa0688df348216558df26.png)

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [April 18, 2022, 9:23am UTC](https://forum.djangoproject.com/t/importing-jquery-file-in-django-template/13228/2 "2022-04-18T09:23:32Z")

</div>

Unless your Javascript file is rendered as a template by Django, this is never going to work. The reason is simple: your `.js` file is not “rendered” by django. It is a static file. Proof is, when you move the Javascript code to your `html` template – it does; the reason is you template is dynamic and aware of what `{% url %}` does.

One way around this (amongst many others) is to have something like this (using data attributes):

```auto
<form data-url="{% url 'my_app:get_form_info' %}" id="my-form">
    <!-- whatever here -->
</form>

```

and in your JS:

```auto
<snip>
var url = document.querySelector('#my-form').dataset.url'
if(!url){
    return
}
// do stuff here
<snip>

```

so:

1. let the HTML template (hence, Django) take care of the url generation.
2. enhance the behaviour using Javascript.

Another, perhaps better way (progressive enhancement and all that), is to listen to the `submit` event of the form? (assuming that’s ok from a functional perspective…):

```auto
var form = document.querySelector('#my-form');
form.addEventListener('submit', function(e){
    var data = new FormData(form);
    fetch(form.action, {
        body: data,
        cache: 'no-cache',
    }).then(function(response) {
        return response.json();
    }).then(function(json){
        console.log(json);
    });
}, false);

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [April 18, 2022, 11:38am UTC](https://forum.djangoproject.com/t/importing-jquery-file-in-django-template/13228/3 "2022-04-18T11:38:03Z")

</div>

First, when posting code here, please do not post images. They’re hard to read on many devices, and can’t be quoted or commented on. Please post your code as text pasted directly into the message, surrounded by lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. (Note, those lines must be lines by themselves - not part of a line of code.) This forces the forum software to keep your code properly formatted.

Second, you generally do _not_ want to render your JavaScript as a Django template. The appropriate way to add data from your view to your page for JavaScript to use is by using the [json\_script tag](https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#json-script).

---

<div class="post-metadata">

**Author:** ![bibalani](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bibalani/32/8165_2.png) [@bibalani](https://forum.djangoproject.com/u/bibalani)\
**Post date:** [April 18, 2022, 6:41pm UTC](https://forum.djangoproject.com/t/importing-jquery-file-in-django-template/13228/4 "2022-04-18T18:41:09Z")

</div>

Thanks. Your answer works when only there is one request for the form. In fact I have two request (GET and POST) for this form. I much appreciate if you help how to handle two request.

```auto
    <div class="container">
        <p>Please Order a Product</p>
        <form id="order_form" method="POST" data-url="{% url 'my_app:get_form_info' 'my_app:add_order_regular_customer' %}">
            {% csrf_token %}
            {{ order_form.as_p }}
            <label for="maximum_quantity">Maximum Quantity</label>
            <br>
            <input class="form-control readonly" type="text" name="" id="maximum_quantity" readonly>
            <br>
            <input class="btn" type="submit" value="Create an Order" name="order_submit">
        </form>
        <br>
        <br>
    </div>

```

ajax

```auto
$(document).ready(function(){
        $('#order_form').change(function(e){
            e.preventDefault();

            var serializedData = $(this).serialize();
            var url = document.querySelector('#order_form').dataset.url
            // var url = "{% url 'my_app:get_form_info' %}"
            $.ajax({
                type: 'GET',
                url: url,
                data: serializedData,
                success: function(response){
                    var current_inventory_fields = response['ser_current_inventory']['current_inventory'];
                    $('#maximum_quantity').val(current_inventory_fields)                                     
                },
                error: function(response){
                    console.log(response)
                }
            });            
        });
    });

    $(document).ready(function(){
        $('#order_form').submit(function(e){
            e.preventDefault();

            var serializedData = $(this).serialize();
            var url = "{% url 'my_app:add_order_regular_customer' %}"
            $.ajax({
                type: 'POST',
                url: url,
                data: serializedData,
                success: function(response){
                    $('#order_form').trigger('reset');

                    var ser_order = JSON.parse(response['ser_order']);
                    var fields = ser_order[0]['fields'];
                    $('#order_info tbody').prepend(
                        `<tr>
                        <td>${fields["id"]||""}</td>
                        <td>${fields["sequence"]||""}</td>
                        <td>${fields["product"]||""}</td>
                        <td>${fields["quantity"]||""}</td>
                        <td>${fields["order_date"]||""}</td>
                        <td>${fields["source"]||""}</td>
                        <td>${fields["destination"]||""}</td>
                        </tr>`
                    )
                    location.reload();
                },
                error: function(response){
                    console.log(response)
                }
            });
            
        });
    });

    $(document).ready(function(){

    });

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [April 18, 2022, 6:48pm UTC](https://forum.djangoproject.com/t/importing-jquery-file-in-django-template/13228/5 "2022-04-18T18:48:39Z")

</div>

I don’t understand what the issue is here. If you have multiple variables to pass from the view to json\_script, then you do it multiple times.

---

<div class="post-metadata">

**Author:** ![bibalani](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bibalani/32/8165_2.png) [@bibalani](https://forum.djangoproject.com/u/bibalani)\
**Post date:** [April 18, 2022, 7:08pm UTC](https://forum.djangoproject.com/t/importing-jquery-file-in-django-template/13228/6 "2022-04-18T19:08:40Z")

</div>

there are two different views and I do not know how I can tag them into my .html and .js files. Using

```auto
data-url="{% url 'my_app:get_form_info' %}"

```

I only can tag get\_form\_info for GET request. However, for POST method I need to tag other view:

```auto
my_app:add_order_regular_customer'

```

I do not know how to tag two views in my form and .js file.

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [April 19, 2022, 8:33am UTC](https://forum.djangoproject.com/t/importing-jquery-file-in-django-template/13228/7 "2022-04-19T08:33:03Z")

</div>

> I do not know how to tag two views in my form and .js file.

You don’t. An HTML form has a “target url” attribute which, when the form is submitted, will be the url to which sent form data will be sent; that attribute is `action`. This is standard, it’s been like this since 1995 or so ([RFC 1866 - Hypertext Markup Language - 2.0](https://datatracker.ietf.org/doc/html/rfc1866#section-8.1.1)). There is not need to re-invent the wheel.

so:

1. `form@action="your_url"` is submitted.
2. Assuming the HTTP method is `POST`, all the data is posted by the client (==browser) (at this stage it is irrelevant whether the “normal” or “js-enhanced” form submit technique is used). Form data is form data and always is when sent over the wire.
3. server receives the `POST` request (this is your django view + form).
4. server validates, etc and then:  
4a. either on error: sends back the original form (in bound state), rendered in a way that is quite similar to step 1. except with error messages, when the form or one of its fields is invalid. `GOTO` 1.( BASIC 😛 )  
4b. OR on success: the form is valid, in which case the server generates a `302` http response and sends back it to the client
5. Client receives the response, which essentially tells it: “go to this url, using the GET method”.
6. Client goes to said url.

To summarise: why do you need “two requests (GET and POST) for this form”? I cannot see a case where you need that.  
Or maybe you need two separate forms?
