2017-01-02 27 views
1

我正在使用以下URL模式將模型的主鍵傳遞給下面詳述的視圖類。相關模型的主鍵「主機」是有效的IP地址或FQDN。儘管對象有效,但包含查詢集時查看返回404

URL模式:

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'] 

有效URL的結果是「找不到與查詢匹配的結果」,由views.HostView引發。下面的視圖成功地調用了{%empty%}條件,這表明我要麼不正確地構造get_object_or_404請求,要麼可能「pk」變量被破壞而不是有效的鍵。

我很感激任何想法的解決方案。或者實際上是實現相同結果的替代方法。

+0

請顯示您的主機型號以及您將要訪問的「有效網址」。 –

+0

將主機模型添加到OP。有效的URL位於本地開發部署中,因此它是127.0.0.1/host/192.168.0.1,IP地址是Host模型的相關PK(「名稱」)。 – jxm

回答

0

原來這個解決方案比預期的簡單得多。我試圖在泛型DetailView中使用get_queryset函數,當它意圖與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 

然後允許我訪問模板中相關的主機模型及其所有相關的查找模型。

相關問題