2017-02-28 162 views
0

我有一個顯示在browseaircraft.html中的飛機列表。用戶點擊標題並進入詳細信息頁面,但是,它不顯示該特定信息的詳細信息,而是顯示所有信息?沒有錯誤消息,但它無法正常運行細節視圖不顯示該帖子的詳細信息? Django

模式

class Aircraft(models.Model): 
    title = models.CharField(max_length=50, default="") 
    cost = models.DecimalField(max_digits=8, decimal_places=3) 
    range = models.IntegerField() 
    cruise_speed = models.IntegerField() 

def get_absolute_url(self): 
    return reverse('aircraftdetail', kwargs={'pk': self.id}) 

網址

urlpatterns = [ 
url(r'^admin/', admin.site.urls), 
url(r'^aircraft', 'aircraft.views.browseaircraft', name='browseaircraft'), 
url(r'^aircraftdetail/(?P<pk>\d+)/$', 'aircraft.views.aircraftdetail', name='aircraftdetail'),] 

查看

def browseaircraft(request): 
    all_aircraft = Aircraft.objects.all() 
    variables = {'all_aircraft':all_aircraft} 
    return render(request,'browseaircraft.html', variables) 

def aircraftdetail(browseaircraft): 
    model = Aircraft 

def aircraft_detail_view(request,pk): 
    try: 
     aircraft_id=Aircraft.objects.get(pk=pk) 
    except aircraft.DoesNotExist: 
     raise Http404("Book does not exist") 
    return render(request,'aircraft_detail.html', 
     context={'aircraft':aircraft_id,} 
    ) 

Browseaircraft.html

{% if all_aircraft%} 
    {% for a in all_aircraft %} 
     <img src="{{a.image.url}}"height="100" width="100"> 
     <a href="{{ a.get_absolute_url }}"> {{ a.title }}</a> 
     {{ a.range }}, 
     {{ a.body }}, 
    {% endfor %} 

aircraft_detail.html

{% block content %} 
    {% for a in all_aircraft %} 
    <h1>Title: {{ a.title }}</h1> 
    {{ a.cost }} 
    {{ a.range}} 
    {{ a.cost }} 
    {{ a.cruise_speed }} 
    {% endfor %} 
{% endblock %} 
+0

是否有任何理由,你爲什麼不理會我完全正確的答案時,你前兩天問這同一個問題? –

回答

0

那麼,你的aircraft_detail.html循環對所有飛機,並顯示他們的信息。如果你想只顯示了一個選定飛機的信息,你需要到HTML頁面更改爲類似這樣:

{% block content %} 
    <h1>Title: {{ aircraft.title }}</h1> 
    {{ aircraft.cost }} 
    {{ aircraft.range}} 
    {{ aircraft.cost }} 
    {{ aircraft.cruise_speed }} 
{% endblock %} 
1

除了問題所指出的其他海報,你有一個問題你的urls.py.您不會終止您的索引視圖的模式,因此它匹配開頭的所有內容,包括「aircraftdetail」的「aircraft」。你應該堅持用$

url(r'^admin/', admin.site.urls), 
url(r'^aircraft/$', 'aircraft.views.browseaircraft', name='browseaircraft'), 
url(r'^aircraftdetail/(?P<pk>\d+)/$', 'aircraft.views. aircraft_detail_view', name='aircraftdetail'),] 
+0

此外,最後一個網址應該使用'aircraft.views.aircraft_detail_view'的適當視圖名稱,而不是'aircraft.views.aircraftdetail' – themanatuf

+1

是的,謝謝,更正。似乎有一個名爲「aircraftdetail」的功能,但我不明白它意味着什麼。 –