safepost
safepost

Reputation: 165

Using django url scheme with Javascript fetch API

I want to use django url scheme when working with fetch API, but it's not understood and i end up with an escaped URL.

I followed this tutorial (in french sorry) in which the author achieve it very easily. Demonstrated here

Example code :

document.querySelectorAll('.list-group-item-action').forEach(
    elem => {
        elem.addEventListener("click", event => {
            event.preventDefault();
            let url = "{% url 'myapp:search_user' %}"
            const request = new Request(url, {method: 'POST', body: formData});
            fetch(request)
               .then(response => response.json())
               .then(result => {
                  console.log(result)
               })
        })
    })

Which ends up with a console error :

POST http://127.0.0.1:8000/myapp/actions/%7B%%20url%20'myapp:search_user'%20%%7D 404 (Not found)

Of course my URL is declared in url.py and works well when used in templates.

If I replace "url" with relative path it's work well, but that's not django friendly.

What I am missing ?

Edit:

Here's the HTML code

{% extends 'myapp/base/base.html' %}

{% load static %}

{%  block headers %}
{% endblock %}


{%  block heading %}
    <h1 class="h3 mb-0 text-gray-800">MyApp - Actions</h1>

{%  endblock %}


{%  block content %}
  <div class="container">
<div class="row">
  <div class="col-lg-4">
    <div class="card">
      <h5 class="card-header">
        {{ title }}
      </h5>


    <form method="POST">
{% csrf_token %}
    </form>
      <div class="list-group list-group-flush">
        {% for action in action_list %}
        <a href="{{ action.dest }}" class="list-group-item list-group-item-action">{{ action.display }}</a>
        {% endfor %}
      </div>
    </div>
  </div>

  <div class="col-lg-5">
    <div class="form-floating">
      <textarea class="form-control" placeholder="Enter list here.." id="user-data" style="height: 150px"></textarea>
      <label for="floatingTextarea2">List</label>
    </div>
  </div>

</div>

  <div class="bg-white col-lg-12" id="target_div">
  </div>


  </div>
{% endblock %}


{% block scripts %}
  <script src={% static "js/actions.js" %}></script>


{% endblock %}

Upvotes: 1

Views: 1592

Answers (2)

I had this same issue when working with ajax and I just used the direct url as it appears on the search bar. Instead of {% url 'myapp:search_user' %} try "mymapp/search_bar" or however it looks in your urls.py file.

Upvotes: 0

Rvector
Rvector

Reputation: 2442

If you want to access to a Django variable on a external Js file

Declare the variable in a js script tag <script> let url = "{% url 'app_label:my_url' %}";</srcipt>

Insert your external js file in which you have now access to the defined url variable

external_js.js

let django_url = url;

Upvotes: 2

Related Questions