Home > Software design >  Django show same content (of a model) in sidebar of every page (also in different apps)
Django show same content (of a model) in sidebar of every page (also in different apps)

Time:11-22

I have two apps: blog and mysite.

In the project folder, I have a template which includes a sidebar template. This sidebar is shown on every page of the project (index pages, mysite pages, blog pages). One part of this sidebar should show a list of the latest x blog entries (independent of the page where the user is).

blog/models.py

class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title = models.CharField(max_length=264)
    text = RichTextField(config_name='detail_text_field', default='')
    created_date = models.DateTimeField(default=timezone.now)

blog/views.py

class LatestBlogEntriesListView(ListView):
    model = Post
    template_name = 'blog/_latest_blog_entries_list.html'

    def get_queryset(self):
        return Post.objects.all().order_by('created_date')[-3:]

sidebar.html

<div class="row">
  {% include 'blog/_latest_blog_entries_list.html' %}
</div>

_latest_blog_entries_list.html

<h4>Latest Blog Entries</h4>

{% for post in objects %}
  <a href="{% url 'blog:post_detail' pk=post.pk %}">{{ post.title }}</a>
{% endfor %}

Unfortunately, this does not work. My sidebar only shows the h4 "Latest Blog Entries", but not the posts. How can I do this?

Any help is highly appreciated!

CodePudding user response:

When using ListView the default object is called object_list. Try changing your code to this:

{% for post in object_list %}
  <a href="{% url 'blog:post_detail' pk=post.pk %}">{{ post.title }}</a>
{% endfor %}

You can also change this variable name in the view, so that when you catch it on the template, it's a custom name.

class LatestBlogEntriesListView(ListView):
    model = Post
    template_name = 'blog/_latest_blog_entries_list.html'
    context_object_name = "your_new_object_name"

CodePudding user response:

I found to use a context processor, as described in this post: https://dev.to/harveyhalwin/using-context-processor-in-django-to-create-dynamic-footer-45k4

This allows to access a context variable within all pages.

  • Related