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

huangapple go评论62阅读模式
英文:

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

问题

It appears you want assistance with your Python code. To address the issue you're facing, you need to extract the ID of the selected category from the request.POST dictionary in your categories_view function. Here's how you can modify your code:

def categories_view(request):
    if request.method == "POST":
        category_name = request.POST["categorys"]
        # Assuming category_name is the name of the category
        try:
            # Try to get the Category object based on the name
            category = Category.objects.get(type=category_name)
            # Now you can access the ID of the category
            category_id = category.id
        except Category.DoesNotExist:
            # Handle the case where the category doesn't exist
            category_id = None

        cg = Listing.objects.filter(category=category_id)
        return render(request, "auctions/Categories_view.html", {
            "category": cg,
        })

In this code, we try to retrieve the Category object based on the category name obtained from the POST request. If it exists, we can access its ID. If it doesn't exist, we set category_id to None or handle it as needed in your specific case. Then, we use this category_id to filter the Listing objects by category ID.

Make sure you've imported the necessary modules and set up your Django project correctly for this code to work.

英文:

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.

答案1

得分: 0

尝试,

cg = Listing.objects.filter(category=c.pk)
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,
        })
英文:

try,

cg = Listing.objects.filter(category=c.pk)
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,
    })

答案2

得分: 0

错误是因为您尝试使用类别名称而不是类别ID来过滤类别,因此您首先需要获取此类别的ID,然后使用它来过滤。
以下是更新后的代码:

def categories_view(request):
    if request.method == "POST":
        category_name = request.POST["categorys"]
        try:
            category = Category.objects.get(name=category_name) # 避免使用c或cg作为变量名
            listings = Listing.objects.filter(category=category)
            return render(request, "auctions/Categories_view.html", {
                "category": listings,
            })
英文:

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,
        })

huangapple
  • 本文由 发表于 2023年6月12日 17:45:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76455407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定