Blog Category Slugify is not working in Django

Viewed 190

I am getting an error when I click on the post category it says Field 'id' expected a number but got 'coding'.

Each post is added under a category below is my Code:

Model:

class Categories(models.Model):
    name = 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_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT)
    slug = models.SlugField(null=False, unique=True) # new

View:

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

URL:

urlpatterns = [
    path('', ItemListView.as_view(), name='waqart-home'),
    path('add_item/', ItemCreateView.as_view(), name='create_item'),
    path('item/<int:pk>/', ItemDetailView.as_view(), name='item_detail'),
    path('item/edit/<int:pk>/', ItemUpdateView.as_view(), name='item_update'),
    path('category/<str:cats>/', CategoryView, name='category'),

I am new to django appreciate if anyone can solve this for me

1 Answers

You need to filter on the name of the item_category, so:

def CategoryView(request, cats):
    category_posts = Item.objects.filter(
        item_category__name=cats.replace('-','')
    )
    return render(request, 'waqart/categories.html', {'cats':cats.title(), 'category_posts':category_posts })
Related