Home > Software design >  How to use exclude filter in django classic view for blog post page?
How to use exclude filter in django classic view for blog post page?

Time:10-20

I'm writing a code for django to list posts in a ListView and DetailView: converting from functional to class view. I can get all the posts to show up, but I want only published posts to show on the list.

I know I can use published = Post.objects.exclude(published_date__exact=None) posts = published.order_by('-published_date')

but how do I get only the posts variable to render in the template, instead of all Post objects in post_list (in list.html template)?

views.py:

from blogging.models import Post
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView


class PostListView(ListView):
    model = Post
    template_name = 'blogging/list.html'

    published = Post.objects.exclude(published_date__exact=None)
    posts = published.order_by('-published_date')



class PostDetailView(DetailView):
    model = Post
    template_name = 'blogging/detail.html'

urls.py

from django.urls import path
from blogging.views import PostListView, PostDetailView

urlpatterns = [
    path('', PostListView.as_view(), name="blog_index"),
    path('posts/<int:pk>/', PostDetailView.as_view(), name="blog_detail"),
]

list.html:

{% extends "base.html" %}{% block content %}
  <h1>Recent Posts</h1>
  {% comment %} here is where the query happens {% endcomment %}
  {% for post in post_list %}
  <div >
    <h2><a href="{% url 'blog_detail' post.pk %}">{{ post }}</a></h2>
    <p >
      Posted by {{ post.author.username }} &mdash; {{ post.published_date }}
    </p>
    <div >
      {{ post.text }}
    </div>
    <ul >
      {% for category in post.categories.all %}
        <li>{{ category }}</li>
      {% endfor %}
    </ul>
  </div>
  {% endfor %}
{% endblock %}

CodePudding user response:

I found the answer:

view.py:

from blogging.models import Post
from django.views.generic.list import ListView
#...

class PostListView(ListView):
    model = Post
    template_name = 'blogging/list.html'

    def get(self, request):
        published = Post.objects.exclude(published_date__exact=None)
        posts = published.order_by('-published_date')
        context = {'post_list': posts}
        return render(request, 'blogging/list.html', context)

CodePudding user response:

You need to override the get_queryset() method in view

class PostListView(ListView):
    model = Post
    template_name = 'blogging/list.html'

    def get_queryset(self): 
        return Post.objects.exclude(published_date__exact=None).order_by('-published_date')
  • Related