本Blog文章例子下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
假设你有一个基于Django的博客网站,其中有文章和分类两个模型。你可以使用以下步骤来查询特定分类下的所有文章并显示文章列表: 1. 首先在models.py文件中定义Article和Category两个模型,如下所示: ```python from django.db import models class Category(models.Model): name = models.CharField(max_length=100) class Article(models.Model): title = models.CharField(max_length=200) content = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE) ``` 2. 在views.py文件中,你需要定义一个视图函数来处理该请求,并查询特定分类下的所有文章,如下所示: ```python from django.shortcuts import render from .models import Article, Category def article_list(request, category_id): category = Category.objects.get(id=category_id) articles = Article.objects.filter(category=category) context = {'category': category, 'articles': articles} return render(request, 'article_list.html', context) ``` 在这个例子中,我们使用category_id参数作为URL中的参数,然后通过该参数查询Category对象。然后,我们使用filter()方法查询所有属于该分类的文章,并将分类对象和文章列表添加到上下文中。 3. 最后,在article_list.html模板中,你可以使用上下文中的数据来显示文章列表,如下所示: ```html <h1>{{ category.name }} Articles</h1> <ul> {% for article in articles %} <li><a href="{% url 'article_detail' article.id %}">{{ article.title }}</a></li> {% empty %} <li>No articles found.</li> {% endfor %} </ul> ``` 在这个模板中,我们使用category.name来显示分类的名称,然后使用for循环显示文章列表。在循环中,我们使用article.title来显示文章的标题,并使用article.id作为URL参数来链接到文章详情页。 这样,当用户访问URL /category/1/时,将会显示属于该分类的所有文章
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值