Search code examples
djangodjango-modelsdjango-viewsdjango-formsdjango-templates

ValueError at /categories_view Field 'id' expected a number but got 'Jewelries'


I want to get listings under a particular category. But when I select the category, I get this error: ValueError at /categories_view Field 'id' expected a number but got 'Jewelries'.

VIEWS.PY

def index(request):
    listings = Listing.objects.filter(is_active=True)
    product_ca = Category.objects.all()
    return render(request, "auctions/index.html", {
        "data": listings,
        "categ": product_ca
    })


def categories_view(request):
    if request.method == "POST":
        c = request.POST["categorys"]
        cg = Listing.objects.filter(category=c)
        cg.category_id
        return render(request, "auctions/Categories_view.html", {
        "category": cg,
    })

MODELS.PY

class Category(models.Model):
    type = models.CharField(max_length=100, null=True)
    
    def __str__(self):
        return self.type
    

class Listing(models.Model):
    product_name = models.CharField(max_length=64, verbose_name="product_name")
    product_description = models.TextField(max_length=200, verbose_name="product description")
    product_image = models.ImageField(upload_to="images/", verbose_name="image", blank=True)
    is_active = models.BooleanField(blank=False, default=True)
    price_bid = models.DecimalField(decimal_places=2, max_digits=6, default=False)
    owner = models.ForeignKey(User, related_name="auction_owner", on_delete=models.CASCADE, default=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category")
    

Seems I'll have id get the id of c = request.POST["categorys"] in Listing but I don't really know how to go about it. Or maybe am still wrong.


Solution

  • The error you encountered because you trying to filter the category with the name of the category not with the id, So you need to get the id of this category first and then filter with it here is he updated code :

    def categories_view(request):
    if request.method == "POST":
        category_name = request.POST["categorys"]
        try:
            category = Category.objects.get(type=category_name) #avoid using c or cg as variables name
            listings = Listing.objects.filter(category=category)
            return render(request, "auctions/Categories_view.html", {
                "category": listings,
            })