1

I'm coding a news website.I have 'category' in News model.

I want to get all the news in one of the categories named 'opinion' in my index.html. And create detail page link for each of them.

I can the title ,author, etc of the news mentioned above .But my brain really junks,I don't know how to create a link points to opinion_new.html or news_detail.htlm for each of them.I have a link for regular news to point to news_detail.htlm.

If you don't quite understand what I'm asking, please also read my last question How to get all the post in the same category in Django you so much!

here is part of my News model:

class News(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="cate", blank=True, verbose_name='分类')

here is my Category model:

class Category(models.Model): name = models.CharField(max_length=40) # 分类名

class Meta:
    verbose_name = "分类"
    verbose_name_plural = verbose_name

def __str__(self):
    return self.name

here is part of my view:

class NewsView(View):

def get(self, request):
    opinion_news = News.objects.filter(category="opinion")

    return render(request, 'index.html', {

        'opinion_news': opinion_news,

    })

here is part of my index.html

        {% for opinion in opinion_news %}
        <li class="media">
          <a href='?'> <h>{{opinion.title}}</h></a>
        </li>
        {% endfor %}

here is part of my already works well news_detail view.

def newsDetailView(request, news_pk):
    news = get_object_or_404(News, id=news_pk)
    category = news.category
    tags = news.tag.annotate(news_count=Count('news'))
    all_comments = NewsComments.objects.filter(news=news)
    news.comment_nums = all_comments.count()
    news.save()

    return render(request, "news_detail.html", {
        'news': news,
        'tags': tags,
        'category': category,

    })

here is my url for news_detail.html

path('-<int:news_pk>', views.newsDetailView, name="news_detail"),
William
  • 3,724
  • 9
  • 43
  • 76

0 Answers0