【发布时间】:2017-04-29 01:18:39
【问题描述】:
我想制作博客,里面有类别和帖子。 应显示类别,当您单击它时,您将被重定向到显示该类别文章的另一个站点。
models.py:
class Category(CMSPlugin):
title = models.CharField(max_length=20, default='category')
def __unicode__(self):
return self.title
class Blog_post(CMSPlugin):
category = models.ForeignKey(Category)
style = models.ForeignKey(Blog_style)
title = models.CharField(max_length=200, default='title')
description = models.CharField(max_length=200,default='description')
image = models.ImageField(upload_to='static', null=True, blank=True)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __unicode__(self):
return self.title
views.py
def Blog_list(request):
posts = Blog_post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
category = Category.objects.all()
return render(request, 'blogspot.html', {'posts': posts, 'category':category})
def post_detail(request, pk):
post = get_object_or_404(Blog_post, pk=pk)
return render(request, 'post_detail.html', {'post': post})
def category_detail(request, pk):
cat = get_object_or_404(Category, id=pk)
post_with_category = Blog_post.objects.filter(category=cat)
return render(request, 'articles.html', {'post_with_category': post_with_category})
blogspot.html
{% for post in posts %}
<h1><a href="{% url 'post_detail' pk=post.pk %}">{{post.title}}</a></h1>
<a href="{% url 'category_detail' pk=post.category.id %}" >{{ post.category }}</a>
{{post.title}}
{{ post.description }}
{{ post.image }}
{{ post.text }}{{ post.published_date }}
{% endfor %}
到目前为止一切正常。我可以点击 {{post.title}} 并重定向到 post_detail。现在我想用类别做同样的逻辑。当我点击{{post.category}}时,我想重定向到articles.html,在那里你可以看到特定类别的所有文章。
编辑:
我插入了代码以按类别显示帖子。我坚持使用 for 循环。如果我使用帖子中提到的循环,我会得到所有帖子和类别。问题是如果我在一个类别中有 2 个帖子,并且此循环将在模板中显示 2x“类别”。
所以我编辑了我的 for 循环。
{% for post in category %}
{{post.title}}
{% endfor %}
如果我在这个循环中插入<a href="{% url 'category_detail' pk=post.category.id %}" >{{post.title}},我就不会得到反向匹配。
我尝试修改views.py category_detail
网址应该看起来像localhost/<category>/
另一个问题是,"select*from Table Where Column_id= id ; 的 QRM 替代命令是什么
urls.py
url(r'^blog/$', views.Blog_list, name='Blog_list'),
url(r'^blog/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
【问题讨论】:
-
在您的 Blog_list 视图中包含
category = Category.objects.all()的原因是什么? -
我打印了模板中的所有类别。如果我使用“帖子”循环,我会得到与我拥有的帖子一样多的打印类别。如果我在 category1 中有 5 个帖子。我的循环打印 5 次 category1
-
您正在打印每个帖子模板中的所有类别?
-
那么,您的问题得到解答了吗?还是您仍然面临问题?
标签: django django-templates django-cms