how can I render a view only when a certain field is True? - Django

Viewed 342

I have created detailed views for the posts in my Django-based blog using the DetailView generic class and everything works fine so far. The problem, however, is that I have a field in my post model that is used to set the status of the posts (active, inactive, blocked) and I only want to render the detailed views when the status is active. If anyone knows of a way to achieve this, please let me know and I ask that you be as detailed as possible.

views.py

from .models import Post
from django.views.generic import DetailView

class PostDetailView(DetailView):
    model = Post
    context_object_name = 'post'
    template_name = 'blog/post-detail.html'

    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        context['title'] = Post.objects.filter(slug=self.object.slug).first()
        return context
1 Answers

In your DetailView you can filter the queryset, for example you can filter with:

from django.views.generic import DetailView

class PostDetailView(DetailView):
    queryset = Post.objects.filter(active=True)

    # …

The DetailView will retrieve the element based on the primary key and/or slug on the queryset, so if the element is not in the filtered queryset, then you will retrieve a 404 error.

Here we assume that the Post model has an active field:

class Post(models.Model):
    # …
    active = models.BooleanField()
    # …

Given the field and values are different, you should of course filter the queryset accordingly.

Related