Reputation: 377
I'm facing a problem with my javascript code when trying to use AJAX instead of href link.
I need to hit a django url that looks like this (Django 2.2):
path('one-time/<str:product_url>/', OneTimeProductView.as_view(), name='one_time_product')
the origial code in the django template was:
<a href="{% url 'one_time_product' product %}">{{product}}</a>
I now want to use ajax call to make the whole process opened inside of a modal. In my javascript code my fetch function looks like this:
function handleAccess(){
var url = "{% url 'one_time_product' product %}" ;
fetch(url, {
method: "POST",
headers: {
"X-CSRFToken": '{{csrf_token}}',
"Accept": "application/json",
"Content-Type": "application/json"
}
})
.then (response => {
response.json();
})
.then (data => {
console.log(data);
})
};
I know i'm missing something related to the params in the url variable but I just don't know how to add it properly so that i fit the url path.
This is the error that I get when I hit the button
NoReverseMatch at /one-time/ Reverse for 'one_time_product' with no arguments not found. 1 pattern(s) tried: ['one\-time\/(?P<product_url>[^/]+)\/$']
How should I write the url in the fetch function ?
I will appreciate and anyone can point me into the right direction here.
Thanks
Upvotes: 0
Views: 1170
Reputation: 377
It was a tricky one. I solved it with the back-end dev.
var url = "{% url 'one_time_product' product_url=0 %}".replace('0', {{ product }}) ;
Upvotes: 1
Reputation: 2478
You have a named parameter in the URL definition (product_url).
On top of my head, you should use the url templatetag like this:
var url = "{% url 'one_time_product' product_url=product.url %}" ;
Change the product.url
to the actual url (or slug) from your product model.
Upvotes: 0