How to create link for one of the category in Django

做~自己de王妃 提交于 2019-12-20 05:50:43

问题


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"),

来源:https://stackoverflow.com/questions/51680988/how-to-create-link-for-one-of-the-category-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!