{{ post.title }}
{{ post.content|truncatewords:30 }}
در یک سایت واقعی، معمولاً لیستی از آیتمها داریم و میخوایم با کلیک روی هر کدوم، به صفحه جزئیات بریم. این کار با لینکها انجام میشه!
بهترین روش برای ساخت لینکها در جنگو، استفاده از تگ url هست:
{% for post in posts %}
{{ post.title }}
{{ post.content|truncatewords:30 }}
{% endfor %}
حالا باید ویوی صفحه جزئیات رو بسازیم:
# blog/views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_detail(request, post_id):
post = get_object_or_404(Post, id=post_id, published=True)
context = {
'post': post
}
return render(request, 'blog/post_detail.html', context)
{{ post.title }}
نویسنده: {{ post.author.username }}
تاریخ: {{ post.created_at|date:"Y/m/d H:i" }}
<hr>
{{ post.content|linebreaks }}
بازگشت به صفحه اصلی
<br> تبدیل میکنه. برای نمایش متنهای چند خطی خیلی مفیده!
یک صفحه جزئیات برای دستهبندی بسازید که تمام پستهای اون دستهبندی رو نمایش بده. از get_object_or_404 استفاده کنید.
برای تثبیت یادگیری این درس تمرینهای زیر را حل کنید
یک صفحه جزئیات برای دستهبندی بسازید که تمام پستهای اون دستهبندی رو نمایش بده.
from django.shortcuts import render, get_object_or_404
from .models import Category, Post
def category_detail(request, category_slug):
# پیدا کردن دستهبندی (یا 404)
category = get_object_or_404(Category, slug=category_slug)
# گرفتن پستهای منتشر شده این دستهبندی
posts = Post.objects.filter(
category=category,
published=True
).order_by('-created_at')
context = {
'category': category,
'posts': posts
}
return render(request, 'blog/category_detail.html', context)
این درس را به پایان رساندید و میتوانید به درس بعدی بروید.