0

Hello friends, I am building a website with Django, I decided to create a filter for my items, you can filter items like this: Item.objects.filter(type=item_type), so basically I created an url which takes a slug:item_type, and returns a JsonResponse with the items parsed as JSON.

Then I created an Ajax call in my js file and when I wanted to call the url to filter by type I keep getting an error:

function filterItemType(type) {
$.ajax({
    type: "GET",
    data: $(this).serialize(),
    url: "{% url 'boring:filter_items' type%}",
...

The Error:

Not Found: /boring/{% url 'boring:filter_items' type%}
[21/Jun/2021 11:32:54] "GET /boring/%7B%%20url%20'boring:filter_items'%20type%%7D HTTP/1.1" 404 6103

So basically, for my understanding, JS is not parsing the Django {% url .... %}. I have no idea how to do it in order for JS to build the route...like I usually do it in the Templates...

PS: I also tried to build the route with the type separated as -> url: "{% url 'boring:filter_items' %}" + "/"+ type; But it's not working either, same error.

Github Issue for this matter...

  • Does this answer your question? [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Abdul Aziz Barkat Jun 21 '21 at 11:50
  • Thanks for the comment, I get the idea, although I find it very strange that there isn't any built in's for this matter, then how are we supposed to "build" the url to make the request? Because if I just simply put: url: "boring/boring:filter_items/"+type It works , but the url is Static. If you want you can check the Guthub issue, there it is what I did, but I wanted to see if there is a solution for building django url in js. – Pulgamecanica Jun 21 '21 at 12:00
  • I would consider the best strategy would be to simply render the url in the HTML as an attribute on some tag and get it from there. For instance `$(this).serialize(),` suggests you are using a form tag, why not simply render the url on the forms `action` attribute? – Abdul Aziz Barkat Jun 21 '21 at 12:01
  • 1
    That is actually a very good idea! :O I will see if I can implement it! Thanks, friend! – Pulgamecanica Jun 21 '21 at 12:07
  • So I actually solved it!!! Not what you usggested, but I took your idea and placed it in my mind, then I came up with a clever solution: https://github.com/pulgamecanica/BoringDjango/commit/7b32773c8c5e8c7fc054d7a34d0eb12ce8df3e63 – Pulgamecanica Jun 21 '21 at 13:00

1 Answers1

1

Basically the solution is to pass the built url in the TEMPLATE and then you can use it in the JS Ajax call. For example:

<profile.html>

onclick=filterItemType("{% url 'boring:filter_items' 'Common'%}")

<profile.js>

function filterItemType(url_type) {
$.ajax({
    type: "GET",
    url: url_type,