0
votes

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)
1
you need to create a base template that contains the elements that should appears on every page such as navbar, and the the other template extends from it, read about it heremohammedgqudah
please read correctly. i'm doing this already. i'm just talking about to pass the same database data for every template or view.. @mohammedqudahuser5721897
i am sorry, did you know about custom template tags? read about them i think they will help youmohammedgqudah

1 Answers

0
votes

You have to create a base template and extend it in every page. read template inheritance

If you want to display some values in the base template (ie display the value in every page), use django's context processors. Read about this here

How to create a context processor