Bryce Morrow Bryce Morrow - 24 days ago 5
Ajax Question

Using Ajax Button to Filter Django Models

I am attempting to make buttons on my website that, when clicked, apply a specific filter to my database of models. The model item I would like to sort is a "Clothes_Item" and I would like to apply various sorts of filters. I just want to get this working on a very basic level and then I'll be able to figure it out from there, so let's just say I want to have a singular button that will display all clothing items with gender = "unisex" (where gender is a field of my Clothes_Item model).

index.html

<input class="filter-button" type="button" data="unisex" value="unisex" data_url/>


main.js

$('.filter-button').on('click', function(event) {
event.preventDefault();
var element = $(this); //button that was clicked
$.ajax({
url : 'filter_clothes/',
type: 'GET',
data: { filter_category : element.attr("data") },
});


urls.py

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'filter_clothes/', views.filter_clothes, name='filter_clothes'),
#more urls...


views.py

def filter_clothes(request):
filter_category = request.GET.get("filter_category")
clothes = Clothes_Item.objects.filter(gender=filter_category)
return HttpResponseRedirect(reverse('index', kwargs={'clothes': clothes}))

def index(request, **kwargs):
clothes = Clothes_Item.objects.all()
if 'clothes' in kwargs:
clothes = kwargs['clohtes']
if request.user.is_authenticated():
favorite_clothes_ids = get_favorite_clothes_ids(request)
return render(request, 'index.html', {'clothes': clothes, 'favorite_clothes_ids': favorite_clothes_ids})
return render(request, 'index.html', {'clothes': clothes})


I'm recieving a "NoReverseMatch at /filter_clothes/" error and I haven't been able to fix this for awhile. Any help would be greatly appreciated!

EDIT: The above issue has been fixed but I didn't completely resolve the issue. The new error is as follows: Reverse for 'index' with arguments '()' and keyword arguments '{'clothes': ]>}' not found. 1 pattern(s) tried: ['$']

Answer

You need to change a regexp pattern for index view in urls.py, as it matches just empty string, but you pass clothes argument to it. For example, if clothes consists of alphanumeric characters, you can change the pattern to r'^/(?P<clothes>\w+)/$'

EDIT: Instead of filter_clothes view, you could pass a get parameters directly to the index view. So it might look like this:

def index(request):
    clothes = Clothes_Item.objects.all()
    filter_category = request.GET.get('filter_category')
    if filter_category:
        clothes = clothes.filter(gender=filter_category)
    if request.user.is_authenticated():
        favorite_clothes_ids = get_favorite_clothes_ids(request)
        return render(request, 'index.html', {'clothes': clothes, 'favorite_clothes_ids': favorite_clothes_ids})
    return render(request, 'index.html', {'clothes': clothes})