i am trying to make site with django and want to categorize each post and a category list. in the category list every category name will be shown as a list and every category name will be linked to the posts according to their categories.
here is my models.py:
class Category(models.Model):
name=models.CharField(max_length=1000,null=True)
def __str__(self):
return self.name
class Post(models.Model):
title=models.CharField(max_length=200,blank=True,null=True)
author=models.ForeignKey(get_user_model(),on_delete=models.CASCADE,null=True)
body=RichTextField(blank=True,null=True)
image=models.FileField(upload_to="mediaphoto")
topImage=ImageSpecField(source='image',processors=[ResizeToFill(750,300)],format='PNG',options={'quality':60})
date=models.DateField(default=datetime.now, blank=True)
category = models.ForeignKey(Category,on_delete=models.CASCADE,verbose_name="Categories")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail',args={str(self.id)})
here is my views.py:
return render(request, 'post_category.html', {'Category': category})
here is my urls.py:
urlpatterns = [
path('post/<int:pk>/delete/',BlogappDeleteView.as_view(),name='post_delete'),
path('post/<int:pk>/edit/',BlogappUpdateView.as_view(),name='post_edit'),
path('post/new/', BlogappCreateview.as_view(),name='post_new'),
path('post/<int:pk>/',BlogappPostView.as_view(),name='post_detail'),
path('post/<int:pk>/category', views.CategoryDetail, name='category'),
path('search',views.Search,name='search'),
path('',BlogappListView.as_view(),name='home'),
]
here is post_category.html
<h3>{{ category.name }} Category</h3>
{% for c in category %}
<h2 class="card-title">{{post.title}}</h2>
<p class="card-text">{{post.description|truncatechars:400|safe}}</p>
<a href="{% url 'post_detail' post.pk %}" class="btn btn-primary">Read More →</a>
Posted on {{post.date|safe}} by
<a href="/">{{post.author}}</a>
in <a href="/">{{post.category}}</a>
{% endfor %}
here is category_list.html:
{% for c in categories %}
<li>
<a href="{% url 'category' post.pk %}">{{c.name}}</a>
</li>
{% endfor %}
main problem is that category list is not fetching any list from the Category name and when click on the category in a post below, it is not showing the posts related to this category. the category page is showing the category name post like physics category.
i think i messed up with the views.py query or in templates... will you help me on this please? it will be very much appreciated.