Home > Enterprise >  Correct way to deny a user action in django?
Correct way to deny a user action in django?

Time:09-13

I'm developing an e-commerce. Currently, i want to prevent the user from having access to Product DetailView of expired products. I can do this using UserPassesTestMixin, but as I'm not testing any userType, i don't know if it's the best way.

models.py

class ProdutosDetail(UserPassesTestMixin, DetailView):
    model = Produto
    template_name = "produto/produto_detail.html"
    context_object_name = "product"


    def test_func(self):
        try:
            assert self.get_object().expiration_date > date.today()
        except AssertionError:
            return False
        else:
            return True

CodePudding user response:

If the result situation is user unrelated you can omit these in the queryset itself? (resulting in 404s). If there's still 'special' users that should be able to view the objects, you could override 'get_queryset' or use some sort of mixin like you've already suggested.

CodePudding user response:

The user does not need to pass a test, the object, you thus can filter with:

from django.db.models.functions import Now


class ProdutosDetail(DetailView):
    model = Produto
    queryset = Producto.objects.filter(expiration_date__gt=Now())
    template_name = 'produto/produto_detail.html'
    context_object_name = 'product'
  • Related