6

I have a model which I want to display as a Detail view, I have created a list view that has a link that leads to its detailed view. I dont get any errors but the template doesn't render any of the models detail Link to DetailView

<a href="../ancillaries/{{ Ancillary.id }}" > Product </a>

Model

from django.db import models
from django.core.urlresolvers import reverse

class Ancillary(models.Model):
     product_code = models.CharField(max_length=60, null=True)
     type = models.CharField(max_length=120, null=True)
     product = models.CharField(max_length=120, null=True)
     standard = models.CharField(max_length=120,   null=True)
     measurement = models.CharField(max_length=120,  null=True)
     brand = models.CharField(max_length=120,   null=True)

     class Meta:
          verbose_name_plural = "Ancillaries"
     def get_absolute_url(self):
          return reverse('ancillaries')
     def __unicode__(self):
          return u'%s %s %s %s %s %s  %s' % (self.id, self.product_code, self.type, 
                                self.product, self.standard, 
                                self.measurement, self.brand)

View

class AncillaryDetail(DetailView):
    model = Ancillary
    def get_context_data(self, **kwargs):

        context = super(AncillaryDetail, self).get_context_data(**kwargs)

       context['ancillary_list'] = Ancillary.objects.all()
       return context

Urls

url(r'^ancillaries/(?P<pk>\d+)/', AncillaryDetail.as_view(template_name='ancillary-detail.html')),

Template

{% for ancillary_list in object_list %}
{{ Ancillary.product}}
{{ Ancillary.type }}
{{ Ancillary.brand }}
{{ Ancillary.measurement }}
{% endfor %}
4

2 回答 2

14

看起来您好像使用了文档,但错误地修改了ListView示例。如果您想显示单个模型实例,那么这DetailView是正确的视图。

正如@mrkre 建议的那样,您应该命名您的 URL 模式(尽管我会使用单数形式的名称)。

url(r'^ancillaries/(?P<pk>\d+)/', AncillaryDetail.as_view(
                template_name='ancillary-detail.html'), name="ancillary_detail")

然后视图很简单

class AncillaryDetail(DetailView):
    model = Ancillary

在模板中ancillary-detail.html,您使用默认名称访问模型实例object

{{ object.product}}
{{ object.type }}
{{ object.brand }}
{{ object.measurement }}
于 2013-08-20T12:19:21.870 回答
5

尝试:

{% for ancillary in ancillary_list %}
    {{ ancillary.product}}
    {{ ancillary.type }}
    {{ ancillary.brand }}
    {{ ancillary.measurement }}
{% endfor %}

我建议使用 url 的名称:

url(r'^ancillaries/(?P<pk>\d+)/', AncillaryDetail.as_view(), name="ancillary_details")

<a href="{% url 'ancillary_details' pk=ancillary.pk %}">

将其放在您的 DetailView 之后

template_name='ancillary-detail.html'
于 2013-08-20T07:26:06.260 回答