我想讓博客裏面有類別和帖子。 類別應顯示,並且當您點擊它時,您將被重定向到顯示此類別的文章的另一個網站。重定向主鍵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