Zack Plauché
Zack Plauché

Reputation: 4280

Django DetailView but get_object_or_404() instead of get_object()

I have Django Model that has a live boolean attribute.

I want the View to get the Model by slug and only go to this page if it's live USING THE DetailView (not function based view, because I want to see how to do it.

Model definition

# myapp/models.py

class MyModel(models.Model):
    name = models.CharField(max_length=255)
    live = models.BooleanField(default=True)
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)

I hoped it would be done something like this:

class ModelDetailView(DetailView):
    model = MyModel
    
    def get(self, request, *args, **kwargs):
        service = self.get_object_or_404(Service, live=True)  # <- Main point of what I'm looking for help with
        return super().get(request, *args, *kwargs)

Is there a way to filter this way?

Upvotes: 1

Views: 802

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

You can specify the queryset to filter, so:

class ModelDetailView(DetailView):
    model = MyModel
    queryset = MyModel.objects.filter(live=True)

You thus do not need to implement the .get(…) method at all.

Upvotes: 2

Related Questions