I'm coding a blog website with Django and everything's looking good until now but I remember something about Django: DRY (Don't repeat yourself) but in my case, it's exactly what I'm doing.
For example, I have a widget to show the recent posts for my blog. This widget appears on every single or index page of my blog and I couldn't do this with include because when I include something, it can't detect the block tags or its content. So I'm writing a code block for this in every another page like category-index, blog-single-page, etc. And the more important one is that I'm adding the database codes to pull data from database and every view def contains this code to show the widget's data so it's against to DRY principle.
Any good way to do this or this is the normal way? Thanks!
Here is the view to give you an idea:
def category_detail(request, category_slug):
posts = Post.objects # FOR BLOG POSTS WIDGET
categories = Category.objects.all() # FOR CATEGORIES WIDGET
category = get_object_or_404(Category, slug=category_slug)
category_posts = category.post_set.all()
paginator = Paginator(category_posts, 10)
page = request.GET.get('page')
cat_posts = paginator.get_page(page)
context = {
'posts': posts.order_by('is_pinned', '-published')[:20],
'popular_posts': posts.order_by('is_pinned','-views')[:15],
'categories': categories,
'category': category,
'category_posts': cat_posts,
}
return render(request, 'blog/category.html', context)
def blog_search(request):
[...]
posts = Post.objects # AGAIN, FOR LATEST POSTS WIDGET
categories = Category.objects.all() # AND AGAIN, FOR CATEGORIES WIDGET
paginator = Paginator(search_posts, 10)
page = request.GET.get('page')
search_posts = paginator.get_page(page)
context = {
'posts': posts.order_by('is_pinned', '-published')[:20],
'popular_posts': posts.order_by('is_pinned','-views')[:15],
'categories': categories,
'search_posts': search_posts,
}
return render(request, 'blog/search.html', context)