在url.py中,
path('server/' , views.ServerView.as_view(),name='serverview'),
在view.py中,
class ServerView(models.Model):
def get(self, request):
qst_disks = DiskInfo.objects.all()
return render(request, 'cmdb/disk-list.html', {
"diskinfo": qst_disks
})
ListVIew
基本方法
class ArticlePostListView(ListView):
# 指定获取数据的 model
model = ArticlePost
# 指定模板语言中使用的变量名
context_object_name = 'postList'
# 指明模板名称
template_name = 'blog/post-list.html'
通过取数据库的值进行过滤
class ArticlePostListView(ListView):
queryset = ArticlePost.objects.order_by("-id")
context_object_name = 'postList'
template_name = 'blog/post-list.html'
动态获取uid
class ServerDListView(ListView):
context_object_name = "serverList"
template_name = 'cbv/server-list.html'
def get_queryset(self):
'''动态获取uid,格式为/server-list/2/,当然格式与url有关'''
# server_id = self.kwargs['uid'] #(1)
'''动态获取uid,格式为?uid=1'''
server_id = self.request.GET.get('uid') #(2) 与urls.py中相匹配
return Server.objects.filter(id__lte=server_id)
在path.py:
path('server-list/', views.ServerDListView.as_view(), name="serverList"), #(2)
path('server-list/<int:uid>/', views.ServerDListView.as_view(), name="serverList"), #(1)
添加额外的数据
class ServerNowListView(ListView):
model = Server
context_object_name = "serverList"
template_name = 'cbv/server-list.html'
'''重写context方法,由于context得到的为字典,因此在context中添加now使用的为字典的添加方法'''
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
return context
DetailView
有条件的筛选
在urls.py中:
path('server-detail/<slug:pk>/',views.ServerDetailView.as_view(),name='serverdetail'),
在views中:
class ServerDetailView(DetailView):
model = Server
context_object_name = "server"
template_name = "cbv/server-detail.html"
在server-detail.html中:
通过循环取值时,使用'.'的方法
{% for servers in server.memory.all %}
在点击详情跳转时
通过获取详情所在的id到所在的数据库取值。因此,在包含详情的页面的点击事件需要返回参数
<td><a href = "{% url 'cbv:serverdetail' server.id %}">详情</a></td>
网友评论