The request failed to reach my Django view
This is a web Django project, In my navbar I have a drop down that contains buttons to exploring products depending on their category, here is the code of the drop down list snippet in the main template:
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Product Categories
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<button data-category = "cloths" class="product-category dropdown-item btn btn-light">Cloths</button>
<button data-category = "sport" class="product-category dropdown-item btn btn-light">Sport</button>
<button data-category = "household items" class="product-category dropdown-item btn btn-light">Household items</button>
</div>
</li>
and I used csrf token for post requests, and here is the javascript snippet:
var productCategories = document.getElementsByClassName("product-category")
for ( i = 0 ; i < productCategories.length ; i ++ )
{
productCategories[i].addEventListener('click', function(){
var category = this.dataset.category
console.log(category)
exploringCategory(category)
})
}
function exploringCategory(category)
{
var url = 'category_exploring/'
fetch(url,{
method:'POST',
headers:{
'Content-Type' : 'application/json',
'X-CSRFToken': csrftoken,
},
body:JSON.stringify({'category' : category})
})
}
and here is the view:
def category_exploring(request):
data = json.loads(request.body)
category = data['category']
print('*')
print(category)
user = request.user
products = Product.objects.filter(category=category)
order, created = Order.objects.get_or_create(customer = user, complete = False)
cartItems = order.get_total_order_cnt
context = {'products' : products, 'cartItems': cartItems}
return render(request, 'store/store.html', context)
the problem is nothing is happening when I click the buttons, what should I do?
I see you are trying to render a template in the category_exploring() function so why not just create an a tag that points to that url. this way no js and no post requests are necessary...
<a href="{% url 'category_exploring' 'cloths' %}" data-category = "cloths" class="product-category dropdown-item btn btn-light">Cloths</a>
<a href="{% url 'category_exploring' 'sport' %}" data-category = "sport" class="product-category dropdown-item btn btn-light">Sport</a>
<a href="{% url 'category_exploring' 'household-items' %}" data-category = "household items" class="product-category dropdown-item btn btn-light">Household items</a>
just update the category_exploring() function to accept the category_slug and do all the filtering with this variable...
def category_exploring(request, category_slug):
pass
and the url
path("category_exploring/<category_slug>/list", category_exploring, name='category_exploring')