Search code examples
pythondjangocontent-management-systemblogs

Django Field 'id' expected a number but got 'coding'


I am getting errors while trying to display all the posts related to one category. Error Message: Field 'id' expected a number but got 'coding'

View Code:

def CategoryView(request, cats):
    category_posts = Item.objects.filter(item_category=cats)
    return render(request, 'waqart/categories.html', {'cats':cats, 'category_posts':category_posts })

URL:

path('category/str:cats/', CategoryView, name='category'),

Template File:

{%extends 'waqart/base.html' %}
{% block content %}
<h1>{{cats}}</h1> 
<div class="flex flex-wrap">
{% for item in category_posts %}

  <h2 class="text-gray-900 text-xl title-font font-medium"{{item.title|truncatechars:40}}</h2>

{% endfor %}

</div>

{% endblock content %}

Model:

class Categories(models.Model):
    name = models.CharField(max_length=200)
    summary = models.CharField(max_length=200)
    slug = models.CharField(max_length=200)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        

        return self.name



class Item(models.Model):
    title = models.CharField(max_length=100)
    description= RichTextField(blank=True, null=True)
    main_image= models.ImageField(null=True, blank=True,upload_to='images/')
    date = models.DateTimeField(auto_now_add=True)
    item_slug = models.CharField(max_length=200, default=1)
    item_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT)

Solution

  • If you filter on the ForeignKey, then Django will filter on the primary key of the target object, and that is normally an AutoField, unless you referred to another (unique) column, or defined another primary key as field.

    You likely want to filter on the slug of the category:

    def CategoryView(request, cats):
        category_posts = Item.objects.filter(item_category__slug=cats)
        return render(
            request,
            'waqart/categories.html',
            {'cats':cats, 'category_posts':category_posts }
        )

    If you need to fetch the category as well, we can do this in two queries with:

    from django.shortcuts import get_object_or_404
    
    def CategoryView(request, cats):
        category = get_object_or_404(Category, slug=cats)
        category_posts = Item.objects.filter(item_category=category)
        return render(
            request,
            'waqart/categories.html',
            {'category': category, 'category_posts':category_posts }
        )