سؤال

I have one silly Django template question; want to create simple sidebar with last "news" and include it in multiple pages in my website. So i do something like this:

# views.py 
def right_sidebar_news(request):
    e = Entry.objects.last()
    return render(request, "_right_sidebar_news.html", {"entry": e})

I include _right_sidebar_news.html in my templates like this:

# some_theme.html
<!-- RIGHT COLUMN -->
{% include "_right_sidebar_news.html" %}
<!-- END RIGHT COLUMN -->

But in almost all pages (except entry details of course) variable "entry" is empty. I know about with statement but in this case i must load last "entry" in all my views.

Any idea how i create this simple sidebar and feel it with data? Thanks.

هل كانت مفيدة؟

المحلول

This is exactly what inclusion tags are for.

نصائح أخرى

As I understand you have your data in right_sidebar_news view? You have to have your desired Entry objects in all templates that include _right_sidebar_news.html so that this Entry could be rendered.
I'd go in a class-based view:

class EntriesViewMixin(object):
    def get_context_data(self, **kwargs):
        context = super(EntriesViewMixin, self).get_context_data(**kwargs)
        context.update({'last_entry': Entry.objects.last()})
        return context

class SomeView(EntriesViewMixin, TemplateView):
    template_view = 'some_theme.html'

But I'm not sure if I understand the question correctly.
Hope that helped :)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top