我使用以下网址格式将模型的主键传递给下面详细介绍的视图类。相关模型的主键" Host"是有效的IP地址或FQDN。
网址格式:
ValidIpAddressRegex = "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"
ValidHostnameRegex = "(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])"
url(r"^host/(?P<pk>({}|{}))/$".format(ValidIpAddressRegex, ValidHostnameRegex),
views.HostView.as_view(),
name="host")
查看课程:
class HostView(generic.DetailView):
model = Host
template_name = 'report_viewer/host.html'
context_object_name = 'related_findings'
def get_queryset(self):
"""Return all related findings"""
host = get_object_or_404(Host, name=self.kwargs["pk"])
return host.get_findings() # A function on the model to return related records from another model
相关模板:
<ul>
{% for finding in related_findings %}
<li><a href="{% url 'report_viewer:finding' finding.plugin_id %}"><strong>{{ finding.plugin_id }}</strong> {{ finding.plugin_name }}</a></li>
{% empty %}
<li>No findings!</li>
{% endfor %}
</ul>
主机型号:
class Host(models.Model):
name = models.CharField(max_length=255, primary_key=True)
os_general = models.CharField(max_length=255, blank=True, verbose_name="Generic OS Identifier")
os_specific = models.CharField(max_length=255, blank=True, verbose_name="Reported OS Name")
ssh_fingerprint = models.CharField(max_length=255, blank=True, verbose_name="SSH Fingerprint")
mac_address = models.CharField(max_length=17, blank=True, verbose_name="MAC Address")
ip_address = models.GenericIPAddressField(blank=True, null=True, verbose_name="IP Address")
fqdn = models.CharField(max_length=255, blank=True, verbose_name="Fully Qualified Domain Name")
netbios_name = models.CharField(max_length=255, blank=True, verbose_name="NetBIOS Name")
def __str__(self):
return self.name
def get_findings(self):
findings = Finding.objects.filter(targets=self)
return findings
class Meta:
ordering = ['name']
有效网址的结果是&#34;找不到匹配查询的搜索结果&#34;,由views.HostView引发。下面的视图成功运行,调用{%empty%}条件,这表明我正确地构造了get_object_or_404请求,或者可能是&#34; pk&#34;变量被破坏,并且不是有效密钥。
我很感激对解决方案的任何想法。或者确实是实现相同结果的另一种方法。
答案 0 :(得分:0)
事实证明,解决方案比预期的要简单得多。我试图将get_queryset
函数与通用DetailView一起使用,当它与ListView一起使用时。
我重写了模型以改为使用get_context_data
函数。
class HostView(generic.DetailView):
model = Host
template_name = 'report_viewer/host.html'
def get_context_data(self, **kwargs):
"""Return all related findings"""
context = super(HostView, self).get_context_data(**kwargs)
context['host'] = get_object_or_404(Host, name=self.kwargs["pk"])
context['findings'] = context['host'].get_findings()
return context
然后,我可以在模板中访问相关的主机模型及其所有相关的查找模型。