importing jquery file in django template

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

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):

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

and in your JS:

<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…):

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);
1 Like

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.

1 Like

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.

    <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

$(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(){


    });

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.

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

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:

my_app:add_order_regular_customer'

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

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). 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 :stuck_out_tongue: )
    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?