【发布时间】:2021-12-22 18:19:47
【问题描述】:
我的博客在每篇博文中都有多个食谱。而且这些食谱在所有博客文章中都多次使用。
我正在尝试创建一个可以在网格中显示所有食谱的页面。一旦访问者点击一个食谱,我希望它链接到数据库中包含该特定食谱的第一篇博客文章。因为我的每篇博文都有 html 页面,但不是每个食谱都有。
我无法想象这将如何构建和完成。我应该重新设计模型还是有办法使用 django 模板来做到这一点?任何帮助将不胜感激!
models.py
class Posts(models.Model):
title = models.CharField(max_length=155)
summary = models.TextField(blank=True, null=True)
slug = models.SlugField(unique=True, max_length=155)
class PostRecipes(models.Model):
post = models.ForeignKey('Posts', models.DO_NOTHING)
recipe = models.ForeignKey('Recipes', models.DO_NOTHING)
class Recipes(models.Model):
title = models.CharField(max_length=155)
summary = models.TextField(blank=True, null=True)
content = models.TextField(blank=True, null=True)
views.py
def allrecipes(request):
recipes = Recipes.objects.all()
context = {
'recipes': recipes,
}
return render(request, "All-recipes.html", context)
All-recipes.html
{% for item in recipes %}
<a href="{{ STATIC_URL }}/{{ item.slug }}">{{ item.title }}</a>
{% endfor %}
【问题讨论】:
标签: django django-models django-views django-templates django-orm