ValueError at /category/economy/: Field 'id' expected a number but got 'economy'

I try to add new path and this happen "Field 'id' expected a number but got 'economy'."

in traceback the highlighted line is in the views.py file which i mentioned below.

category_posts = Post.objects.filter(category=cats)

I am sharing my files plz help me to get rid of the issue. urls.py


urlpatterns = [
    path('',views.allpost,name="allpost"),
    path('search', views.search, name="search"),
    path('contact/', views.contact, name="contact"),
    path('success/', views.successView, name="success"),
    path('category/<str:cats>/', views.CategoryView, name ="category"),
    path('<int:blog_id>/',views.detail,name="detail"),
] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)

here i used str:cats, yet it shows "Field 'id' expected a number but got 'economy'."

views.py


def CategoryView(request, cats):   # here cats is same which mentioned in dynamic url.
    category_posts = Post.objects.filter(category=cats)
    return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})

"category_posts = Post.objects.filter(category=cats)" this line of code shows in traceback

models.py

from django.db import models

class Category(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
    title = models.CharField(max_length=255, verbose_name="Title")
    parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=
    True, null=True)

    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"
        ordering = ['title']

    def __str__(self):
        return self.title


class Post(models.Model):
    
    title = models.CharField(max_length=100)
    public_date = models.DateField(null=True)
    public_time = models.TimeField(null=True,default="")
    category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Category", null=True)
    image = models.ImageField(upload_to='images/',null=True, blank=True)
    body = models.TextField()

    class Meta:
        verbose_name = "Post"
        verbose_name_plural = "Posts"
        ordering = ['public_date']

    def summary(self):
        return self.body[:100]

    def pub_date(self):
        return self.public_date.strftime('%b %e,%y')
    # to give layout for time and date

    def __str__(self):
        return self.title

categories.html

{% extends 'base.html' %}



{%block content%}

<h1> Category: {{ cats }} </h1>


{% for post in category_posts %}



<div class="container mt-3">
    <div class="row mb-2">
        <div class="col-md-6">
          <div class="card flex-md-row mb-4 box-shadow h-md-250">
            <div class="card-body d-flex flex-column align-items-start">
              <strong class="d-inline-block mb-2 text-primary">{{ post.category }}</strong>
              <h3 class="mb-0">
                <a class="text-dark" href="{% url 'detail' post.id %}">{{post.title}}</a>
              </h3>
              <div class="mb-1 text-muted">{{ post.public_date }}</div>
              <p class="card-text mb-auto">{{ post.summary }}</p>
              <a href="{% url 'detail' post.id %}">Continue reading</a>
            </div>
            <img class="card-img-right flex-auto d-none d-md-block" data-src="holder.js/200x250?theme=thumb" alt="Thumbnail [200x250]" style="width: 200px; height: 250px;" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22200%22%20height%3D%22250%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20200%20250%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_182c981dfc3%20text%20%7B%20fill%3A%23eceeef%3Bfont-weight%3Abold%3Bfont-family%3AArial%2C%20Helvetica%2C%20Open%20Sans%2C%20sans-serif%2C%20monospace%3Bfont-size%3A13pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_182c981dfc3%22%3E%3Crect%20width%3D%22200%22%20height%3D%22250%22%20fill%3D%22%2355595c%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2256.20000076293945%22%20y%3D%22131%22%3EThumbnail%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">
          </div>
        </div>

    </div>
</div>



{% endfor %}

{% else %}
    <h2>Sorry this page does not exist....</h2>
{% endif %}



{%endblock%}


I am confused it demands. can someone help me to solve it plz.

Its because you are querying it wrong: So instaed of doing this:

# views.py 

def CategoryView(request, cats):   # here cats is same which mentioned in dynamic url.
    category_posts = Post.objects.filter(category=cats)
    return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})

Try something with this query. I'm supposing you want to query all the posts of a specific category that will be coming from your URL.

from django.shortcuts import get_object_or_404


def CategoryView(request, cats):
    # method 1
    category_posts = Post.objects.filter(category__title=cats)
    # method 2
    category = Category.objects.get(title=cats)
    category_posts = category.Category.all() # here .Category is the related_name you used in your Post model
    
    # method 3:
    category = get_object_or_404(Category, title=cats) # will raise 404 if no category found with the given title
    category_posts = category.Category.all()
    
    return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})

PS: When you don't know what your ForeignKey related_name should be. Then go for the plural name of the model. Like in the current case:

# models.py

category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="posts", null=True)

This way we can query like this category_posts = category.posts.all()

Back to Top