Home > Mobile >  Django ListView: how to show few entry and protect the other
Django ListView: how to show few entry and protect the other

Time:10-01

I have a model with few entries. I'd like to show only few of them and protect the others... example:

class Squadra(models.Model):
    ...
    tipo = models.IntegerField(choices=TIPO_SQUADRA, default=1)
    ...

Then I have a ListView which return only few Squadra objects using a filter:

all_squadre = Squadra.objects.filter(tipo=3)

and a url file including this:

    path('squadra_table/<int:squadra>/', views.SquadraTableListView.as_view() ),

My problem is that someone could get to the Squadra page and then he could try to change randomly the ID <int:squadra> in the url and access other entries which I'd like to keep protected... How can I do that?

Thanks for helping

Attilio

CodePudding user response:

To protect your view you need to override the dispatch method and put some logic based on your need, for example :

class ProtectedView(TemplateView):
    template_name = 'secret.html'


    def dispatch(self, request, *args, **kwargs):
        entity = get_object_or_404(Entity, pk=args[0])
      if not check_permission(request, entity):
       raise Http404
      return super(MyView, self).dispatch(request, *args, **kwargs)
  • Related