How to restrict access to objects using detailview class

守給你的承諾、 提交于 2019-12-11 06:08:21

问题


Im trying to limit the display objects to the user who created it. Is it done using a foreign key in the object model?

Ex: User 1 may access object 1 User 2 may access object 2

At this moment any user can access any object just entering the correct URL to that object.

File views.py

from django.shortcuts import render
from django.http.response import Http404
from .models import Host
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.contrib.auth.decorators import login_required
# Create your views here.


def index(request):
    return render(request, 'index.html')


class HostDetail(DetailView):

    model = Host

    def get_context_data(self, **kwargs):
        context = super(HostDetail, self).get_context_data(**kwargs)
        return context


class HostList(ListView):

    model = Host

    def get_queryset(self, **kwargs):

        qs = super(HostList, self).get_queryset(**kwargs).filter(perfil=self.request.user.perfil.id)
        return qs

File models.py

class Perfil(models.Model):

    usuario = models.OneToOneField(User, on_delete=models.CASCADE)
    zbx_user = models.CharField(max_length=255, null=False)
    pwd = models.CharField(max_length=255, null=False)
    nome = models.CharField(max_length=255, null=False)
    grupo = models.CharField(max_length=255, null=False)
    numero_hosts = models.IntegerField(null=True)

    def __str__(self):

        return self.nome

class Host(models.Model):

    host_name = models.CharField(max_length=120)
    templateid = models.PositiveIntegerField()
    tipo = models.PositiveIntegerField()
    ip = models.GenericIPAddressField()
    dns = models.CharField(max_length=120, default="")
    host_id = models.PositiveIntegerField()
    # Relacionamento 1 pra N com Perfil
    perfil = models.ForeignKey(Perfil, on_delete=models.CASCADE)

    def __str__(self):
        return self.host_name

File urls.py

from django.conf.urls import url
from . import views
from django.conf.urls.static import static
from django.conf import settings
from .views import HostDetail, HostList

urlpatterns = [

    # Rota para index perfis
    url(r'^$', views.index, name='index'),
    url(r'^host/(?P<pk>\d+)$', HostDetail.as_view(), name='HostDetail'),
    url(r'^host/$', HostList.as_view(), name='HostList'),

Thanks


回答1:


Use the same approach as you use for the ListView. Filter the queryset using self.request.user.

You may also want to use LoginRequiredMixin on both views, so that only logged-in users can access the views.

from django.contrib.auth.mixins import LoginRequiredMixin

class HostDetail(LoginRequiredMixin, DetailView):
    model = Host

    def get_queryset(self):
        qs = super(HostList, self).get_queryset().filter(perfil=self.request.user.perfil_id)
        return qs

    ...



回答2:


Override the dispatch() method of the DetailView class.

 def dispatch(self, *args, **kwargs):
    # Custom user permission check
    return super(HostDetail, self).dispatch(*args, **kwargs)


来源:https://stackoverflow.com/questions/42695008/how-to-restrict-access-to-objects-using-detailview-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!