Field 'id' expected a number but got 'filter_data'. DJANGO, AJAX

Question:

I am working on filters in my project. Based on the tutorial, I started adding Ajax so that I could filter cards by several categories. Everything was working fine until I added the data and jsonResponse. Now every time I click the checkbox I get this error

Ajax

$(document).ready(function(){
    $(".ajaxLoader").hide()
    $(".filter-checkbox").on('click', function(){
        var _filterObj={};
        $(".filter-checkbox").each(function(index,ele){
            var _filterVal=$(this). val();
            var _filterKey=$(this). data('filter');
            _filterObj[_filterKey]=Array.from(document.querySelectorAll('input[data-filter='+_filterKey+']:checked')).map(function(el){
                return el.value;
            });
        });

        $.ajax({
            url:'filter_data',
            data:_filterObj,
            dataType:'json',
            beforeSend:function(){
                $(".ajaxLoader").show();
            },
            success:function(res){
                console.log(res);
                $("#filteredProducts").html(res.data);
                $(".ajaxLoader").hide();
            }
        });
    });
});

models.py

class Gender(models.Model):
    gender_choices = [('Male', 'Male'), ('Female', 'Female')]
    gender = models.CharField(max_length=6, choices=gender_choices, default='Male')

    def __str__(self):
        return self.gender

class Brand(models.Model):
    title = models.CharField(max_length=100)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return self.title

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url

class Size(models.Model):
    title = models.CharField(max_length=100)

    def __str__(self):
        return self.title

class Color(models.Model):
    title = models.CharField(max_length=100)
    color_code = models.CharField(max_length=100)

    def __str__(self):
        return self.title

class Customer(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, related_name="customer")
    name = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200)

    def __str__(self):
        return self.name


class Product(models.Model):
    gender_choices = [('Male', 'Male'), ('Female', 'Female')]
    name = models.CharField(max_length=200)
    detail = models.TextField()
    color = models.ForeignKey(Color, on_delete=models.CASCADE)
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    size = models.ForeignKey(Size, on_delete=models.CASCADE, blank=True, null=True)
    gender = models.CharField(max_length=6, choices=gender_choices, default='Male')
    price = models.DecimalField(max_digits=10, decimal_places=0)
    status = models.BooleanField(default=True,null=False, blank=False)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url

views.py

def product_view(request, id):
    product = Product.objects.filter(id=id).first()

    data = cartData(request)
    cartItems = data['cartItems']

    data1 = wishData(request)
    wishItems = data1['wishItems']

    context = {'product':product, 'cartItems':cartItems, 'wishItems':wishItems}

    return render(request, 'store/product_view.html', context)

def filter_data(request):
    return JsonResponse({'data':'hello'})


def store(request):
    data1 = wishData(request)
    wishItems = data1['wishItems']

    data = cartData(request)

    cartItems = data['cartItems']


    products = Product.objects.all()

    color = Color.objects.all()
    size = Size.objects.all()
    brand = Brand.objects.all()
    price = Product.objects.values_list('price')

    context = {'products':products, 'cartItems':cartItems, 'wishItems':wishItems,'color':color, 'size':size, 'brand':brand, 'price':price}
    return render(request, 'store/store.html', context)

urls.py

from django.urls import path, include
from django.contrib.auth.views import PasswordChangeView
from . import views
from .forms import PasswordUpdateForm

urlpatterns = [
    path('', views.store, name="store"),
    path('cart/', views.cart, name="cart"),
    path('checkout/', views.checkout, name="checkout"),
    path('login/', views.loginPage, name="login"),
    path('logout/', views.logoutUser, name="logout"),
    path('registration/', views.registrationPage, name="registration"),
    path('profile/', views.profile, name="profile"),
    path('change_password/', PasswordChangeView.as_view(template_name='store/change_password.html', success_url='profile', form_class=PasswordUpdateForm ), name="change_password"),
    path('change_password/profile/', views.profile, name="profile"),

    path('update_item/', views.updateItem, name="update_item"),
    path('update_wish_item/', views.updateWishItem, name="update_wish_item"),
    path('process_order/', views.processOrder, name="process_order"),
    path('<str:id>', views.product_view, name="product_view"),
    path('wishlist/', views.wishlist, name="wishlist"),
    path('search/', views.search, name="search"),
    path('filter_data/', views.filter_data, name="filter_data"),
    path('search/<str:id>',views.product_view, name="product_view"),

]

Error

Traceback (most recent call last):
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangocorehandlersexception.py", line 56, in inner
    response = get_response(request)
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangocorehandlersbase.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:UsersAdminPythonProject 555bootsstoreviews.py", line 118, in product_view
    product = Product.objects.filter(id=id).first()
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelsmanager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelsquery.py", line 1421, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelsquery.py", line 1439, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelsquery.py", line 1446, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelssqlquery.py", line 1532, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelssqlquery.py", line 1562, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelssqlquery.py", line 1478, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelssqlquery.py", line 1303, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelslookups.py", line 27, in __init__
    self.rhs = self.get_prep_lookup()
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelslookups.py", line 341, in get_prep_lookup
    return super().get_prep_lookup()
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelslookups.py", line 85, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "C:UsersAdminPythonProject 555venvlibsite-packagesdjangodbmodelsfields__init__.py", line 2020, in get_prep_value
    raise e.__class__(
ValueError: Field 'id' expected a number but got 'filter_data'.

I actually have no idea how to fix this. What should I add or replace?

Asked By: Poor Cake

||

Answers:

The filter_data endpoint never reached because of this path definition:

path('<str:id>', views.product_view, name="product_view"),

The <str:id> catches almost everything, including filter_data that causes the error message. Furthermore you have a second (the real one?) product_view endpoint under search/<str:id>. You should remove the first one.

Additionally id is a number, so you can use <int:id> at the path definition.

Answered By: Dauros
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.