我一直在尝试在DetailView
中使用多个views.py
,但由于某种原因,我在模板渲染过程中遇到此错误。 http://prntscr.com/7f8vql
http://prntscr.com/7f8vlv。
我的views.py
def rock_and_feat(request):
feats = Feat.objects.order_by('-created')[:3]
rocks = Rockinfo.objects.order_by('-rank')[:50]
context = RequestContext(request, {
'feats': feats, 'rocks': rocks
})
return render_to_response('template.html', context)
class DetailView(generic.DetailView):
model = Feat
template_name = 'feature/detail.html'
context_object_name = 'feat'
class RockDetailView(generic.DetailView):
model = Rockinfo
template_name = 'feature/detailrock.html'
context_object_name = 'rockinfo'
我的应用urls.py
urlpatterns = [
url(r'^$', views.rock_and_feat, name='rock_and_feat'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/$', views.RockDetailView.as_view(), name='detailrock'),
]
我的项目urls.py
urlpatterns = [
url(r'^', include('feature.urls', namespace="feature")),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
template.html
{% block rocker %}
{% if rocks %}
{% for item in rocks %}
<div class="artist-container">
<a href="{% url 'feature:detailrock' rockinfo.id %}"><img src="{{ item.rock_img.url }}" class="artist-img" alt="Dimitri Vegas & Like Mike">
<div class="artist-info">{{ item.rock_name }}</div></a></div>
{% endfor %}
{% else %}
<p>No rockers are available.</p>
{% endif %}
</div></div>
{% endblock %}
我无法弄清楚错误是什么。谢谢
答案 0 :(得分:3)
我记得你关于rock_and_feat
的问题。
我想提几件事:
urlpatterns = [
url(r'^$', views.rock_and_feat, name='rock_and_feat'),
url(r'^detail/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^rock_detail/(?P<pk>[0-9]+)/$', views.RockDetailView.as_view(), name='detailrock'),
]
你没有rockinfo
。它是item
。在这一行:
{% url 'feature:detailrock' item.id %}
还有一件事。请注意,id
is not the same为pk
。
{% url 'feature:detailrock' item.pk %}
最后一件事。这可以替换:
{% if rocks %}
{% for item in rocks %}
....
{% endfor %}
{% else %}
<p>No rockers are available.</p>
{% endif %}
使用此(docs):
{% for item in rocks %}
...
{% empty %}
<p>No rockers are available.</p>
{% endfor %}
答案 1 :(得分:0)
(疯狂猜测)阅读错误,我觉得rockinfo.id
是空的,或者它不存在(或没有传递给模板),你检查过吗?
除此之外,您应该为视图设置两种不同的模式
希望这有帮助
答案 2 :(得分:0)
1.请检查模板以获取rockinfo.id并检查。
<a href="{% url 'feature:detailrock' rockinfo.id %}">
2.从urlconf中删除命名空间,只需在模板中使用
<a href="{% url 'detailrock' rockinfo.id %}">
。我认为1或2都可以。