我想让博客里面有类别和帖子。 类别应显示,并且当您点击它时,您将被重定向到显示此类别的文章的另一个网站。重定向主键django {%url%}
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 %}
到目前为止工作一切ok。我可以点击{{post.title}}并将im重定向到post_detail。现在我想要对类别进行相同的逻辑。当我点击{{post.category}}时,我希望重定向到articles.html,您可以在其中查看特定类别中的所有文章。
编辑:
我插入的代码,以显示类别的职位。我与for循环Stucked。如果我使用后面提到的循环,我会得到所有的帖子和类别。问题是如果我在一个类别中有2个帖子,并且此循环将在模板中显示2个“类别”。
所以我编辑了我的for循环。
{% for post in category %}
{{post.title}}
{% endfor %}
如果我在此循环中插入<a href="{% url 'category_detail' pk=post.category.id %}" >{{post.title}}
,我不会得到反向匹配。 我试图修改views.py category_detail
和URL应该看起来像localhost/<category>/
而另一个问题是,什么是"select*from Table Where Column_id= id ;
urls.py QRM替代COMAND
url(r'^blog/$', views.Blog_list, name='Blog_list'),
url(r'^blog/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
什么是背后的原因包括'类别= Category.objects.all( )'在你的Blog_list视图中? – Doug
我在模板中打印所有类别。如果我使用“帖子”循环,我会得到打印类别尽可能多的帖子。如果我在类别1中有5个职位。我的环印刷5次组别 – OverHeat
要打印所有类别中每一个岗位的模板? – Doug