详细信息视图未显示帖子的详细信息? Django的

时间:2017-02-28 20:34:34

标签: django

我有一个在browseaircraft.html中显示的飞机列表。用户点击标题并进入详细信息页面,但是,它不会显示该特定帖子的详细信息,而是显示所有帖子的详细信息?没有错误消息,但它没有按预期工作

模型

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 %}

2 个答案:

答案 0 :(得分:1)

除了其他海报指出的问题,你的urls.py也有问题。您不会终止索引视图的模式,因此它匹配开始的所有内容&#34;飞机&#34; - 包括&#34; aircraftdetail&#34;。您应该始终使用$

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

答案 1 :(得分:0)

好吧,你的aircraft_detail.html在所有飞机上循环并显示他们的信息。如果您只想显示所选飞机的信息,您需要将html页面更改为:

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