2

I am building a page which holds some categories and when user clicks on a link, then I go ahead and fetch the details for that specific category (products of that category). The way to do this, I thought, was to use jQuery Ajax. Anyway, the part where i append my data is like this:

...
$.ajax({
    ...
    success: function(results) {
        $("#cards").empty();
        for (let iterator = results.length -1; iterator>=0; iterator--) {
            $("#cards").append(
            '<a href="{% url "product" '+results[iterator].id+' %}">'
            +'<div>'
            +    '<div class="card mb-5 shadow-sm">'
            +        '<img class="card-img-top"'
            +             'src="'+results[iterator].image+'" />'
            +        '<div class="card-body">'
            +            '<h5 class="card-title">'+results[iterator].name+'</h5>'
            +            '<p class="card-text">'+results[iterator].price+'</p>'
            +        '</div>'
            +    '</div>'
            +'</div>'
            +'</a>'
            );
        }
    },
    ...
});
...

Based on this block of code, i get this error:

Reverse for 'product' with arguments '('+results[iterator].id+',)' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/$']

Since i get the results in form of json i don't have a problem with using it the way i did, but the problem rises when adding the a tag around my container div. I don't understand what course of action I should take since i'm not really experience with neither Django nor jQuery.

1

1 Answer 1

1

You cannot mix Django templates and JavaScript like that. The Django template is rendered on the server-side, JavaScript is executed in the browser.

When the Django template engine parses {% url "product" '+results[iterator].id+' %}, it treats '+results[iterator].id+' as string and passes it as-is to the url template tag. But this string doesn't match the URL pattern, which is why you are getting this error.

There are various solutions to what you are trying to do. The approach which probably requires the least changes is to return the product URLs in the response of your Ajax request. For an answer on how to do that exactly, you have to post your view.

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

2 Comments

Oh! Thanks, i had trouble understanding server/client renderings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.