我試圖限制顯示對象給創建它的用戶。 它是否在對象模型中使用外鍵完成?如何使用detailview類限制對象的訪問
例如: 用戶1可以訪問對象1個 用戶2可以訪問對象2
此時任何用戶都可以訪問任何對象剛進入正確的URL到該對象。
文件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
文件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
文件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'),
感謝
嗨@Alasdair,它似乎解決了這個問題。但即時通訊我有點困惑,我擺脫'get_context_data()',它工作正常。我什麼時候需要使用它?謝謝! –
我遺漏了'get_context_data',因爲它與問題無關,我並不是說要刪除它。如果要定製上下文,則重寫'get_context_data'僅適用。有關示例,請參閱文檔中的示例(https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-display/#detailview),它將「now」添加到上下文中。在你的情況下,你所做的只是返回'super()'的結果,所以刪除它就可以了。 – Alasdair