Категория Django не отображается
Я делаю блог на django и у меня возникли проблемы с отображением постов, когда они находятся в категориях. Я заставил их работать в category_list.html, чтобы показать категории в списке. Но когда вы нажимаете на категорию, вы должны иметь возможность видеть посты блога в этой категории из categories.html
Я понятия не имею, почему посты категории не отображаются, когда вы входите в категорию. У кого-нибудь есть идеи, в чем может быть проблема?
Я использовал {% for cats in cat_menu_list %} в шаблоне categories для его отображения и думаю, что код:
def CategoryView(request, cats):
cat_menu_list = Post.objects.filter(
category=cats.replace(
'-', ' ')).order_by('-id')
paginator = Paginator(cat_menu_list, 3)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'categories.html', {'cats': cats.replace('-', ' ').title(), 'cat_menu_list': cat_menu_list, 'page_obj': page_obj})
newsapp views.py
newsapp urls.py
from django.urls import path
from .views import (
HomeView,
ArticleDetailView,
AddPostView,
UpdatePostView,
DeletePostView,
CategoryView,
CategoryListView,
LikeView,
AddCommentView)
urlpatterns = [
path(
'',
HomeView.as_view(),
name="home"),
path(
'article/<int:pk>',
ArticleDetailView.as_view(),
name='article-detail'),
path(
'add_post/',
AddPostView.as_view(),
name='add_post'),
path(
'article/edit/<int:pk>',
UpdatePostView.as_view(),
name='update_post'),
path(
'article/<int:pk>/remove',
DeletePostView.as_view(),
name='delete_post'),
path(
'category/<str:cats>/',
CategoryView,
name='category'),
path(
'category-list/',
CategoryListView,
name='category-list'),
path(
'like/<int:pk>',
LikeView,
name='like_post'),
path(
'article/<int:pk>/comment/',
AddCommentView.as_view(),
name='add_comment'),
]
newsapp Models.py
from django.db import models
from cloudinary.models import CloudinaryField
from django.contrib.auth.models import User
from django.urls import reverse
from datetime import datetime, date
from ckeditor.fields import RichTextField
class Category(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('home')
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField()
profile_pic = models.ImageField(
null=True, blank=True, upload_to="images/profile/")
website_url = models.CharField(max_length=255, null=True, blank=True)
facebook_url = models.CharField(max_length=255, null=True, blank=True)
twitter_url = models.CharField(max_length=255, null=True, blank=True)
instagram_url = models.CharField(max_length=255, null=True, blank=True)
pinterest_url = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return str(self.user)
def get_absolute_url(self):
return reverse('home')
class Post(models.Model):
title = models.CharField(max_length=255)
header_image = models.ImageField(
null=True, blank=True, upload_to="images/")
title_tag = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank=True, null=True)
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='code')
likes = models.ManyToManyField(User, related_name='blog_posts')
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('home')
class Comment(models.Model):
post = models.ForeignKey(
Post,
related_name="comments",
on_delete=models.CASCADE)
name = models.CharField(max_length=255)
body = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
шаблон categories.html
{% extends 'base.html' %}
{% block content %}
<h1 class="headerh1">{{ cats }}</h1>
<div class="container">
<div class="row">
<!-- Blog Entries Column -->
<div class="col-md-8 mt-3 left">
{% for cats in cat_menu_list %}
<div class="card mb-4">
<div class="card-body">
<h2 class="card-title"><a href="{% url 'article-detail' post.pk %}" class="text-dark">{{post.title }}</a></h2>
<p class="card-text text-dark h6">{{ post.author.first_name }} {{post.author.last_name }} | {{ post.post_date }}
<a href="{% url 'category' post.category|slugify %}">{{ post.category }}</a></p>
<div class="card-text">{{ post.body|safe|slice:":200" }}</div>
<a href="{% url 'article-detail' post.pk %}" class="btn btn-info">Read More</a>
{% if user.is_authenticated %}
{% if user.id == post.author.id %}
<a href="{% url 'update_post' post.pk %}" class="btn btn-primary">Edit</a>
<a href="{% url 'delete_post' post.pk %}" class="btn btn-danger">Delete</a>
{% endif %}
{% endif %}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
<div class="pagination">
<nav aria-label="Page navigation">
<ul class="pagination justify-content-center">
{% if page_obj.has_previous %}
<li><a href="?page={{ page_obj.previous_page_number }}" class="page-link">« PREV </a></li>
{% endif %}
{% if page_obj.has_next %}
<li><a href="?page={{ page_obj.next_page_number }}" class="page-link"> NEXT »</a></li>
{% endif %}
</ul>
</nav>
</div>
{% endblock %}
шаблон список_категорий
{% extends 'base.html' %}
{% block title %}Blog Categories{% endblock %}
{% block content %}
<h1>Blog Categories</h1>
{% for item in cat_menu_list %}
<h4><a class="dropdown-item list-group-item list-group-item-dark" href="{% url 'category' item|slugify %}">{{ item }}</a></h4>
{% endfor %}
{% endblock %}