我有一个模型,我希望将其显示为详细信息视图,我创建了一个列表视图,其中包含指向其详细视图的链接。我没有得到任何错误,但模板不呈现任何模型细节 链接到DetailView
<a href="../ancillaries/{{ Ancillary.id }}" > Product </a>
模型
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)
查看
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
网址
url(r'^ancillaries/(?P<pk>\d+)/', AncillaryDetail.as_view(template_name='ancillary-detail.html')),
模板
{% for ancillary_list in object_list %}
{{ Ancillary.product}}
{{ Ancillary.type }}
{{ Ancillary.brand }}
{{ Ancillary.measurement }}
{% endfor %}
答案 0 :(得分:13)
您好像使用了documentation,但错误地调整了ListView
示例。如果要显示单个模型实例,则DetailView
是正确的视图。
正如@mrkre建议您应该为您的网址格式命名(虽然我会使用单数形式作为名称)。
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 }}
答案 1 :(得分:4)
尝试:
{% 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'