我的Django项目中存在以下问题:
模板渲染期间出错
在模板中 /home/didier/Documents/Projects/inventory/inv/templates/index.html, 第11行的错误NoReverseMatch at / element Reverse for 带有参数'()'和关键字的'elements.views.element_detail' 没有找到参数'{u'pk':1}'。尝试了0种模式:[]
Views.py 是:
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render, get_object_or_404
from .models import Element
def hello(request):
element = Element.objects.order_by('id')
template = loader.get_template('index.html')
title = 'Element list - RegiX'
context = {
'element': element,
'title': title
}
return HttpResponse(template.render(context, request))
ref element_detail(request, pk):
element = get_object_or_404(Element, pk=pk)
template = loader.get_template('element_detail.html')
context = {
'element': element
}
return HttpResponse(template.render(context, request))
Urls.py :
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^element$', views.hello, name='hello'),
url(r'^detail/(?P<pk>[0-9]+)/$', views.element_detail, name='detail'),
]
的index.html :
{% extends 'base.html' %}
{% load staticfiles %}
{% block page_title %}
Element list | RegiX
{% endblock %}
{% block content %}
<h2>Hello</h2>
{% for el in element %}
<li>
{{ el.manufacturer }} ::
<a href="{% url 'elements.views.element_detail' pk=el.pk %}">
{{ el.model }}
</a>
{{ el.date_purchase }} ::
<img src="{{ el.image.url }}">
</li>
{% endfor %}
{% endblock %}
base.html扩展到index.html:
<!DOCTYPE html>
<html lang="en">
<head>
{% load staticfiles %}
<meta charset="UTF-8">
<title>{% block page_title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/base.css' %}">
</head>
<body>
<header>
<strong>RegiX Enterprise</strong>
</header>
<section>
{% block login_content %}
{% endblock %}
{% block content %}
{% endblock %}
</section>
<footer><small>RegiX :: powered By Didier Zúñiga</small></footer>
</body>
</html>
Urls.py设置:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('elements.urls', namespace='elements')),
url(r'^', include('userprofiles.urls', namespace='userprofiles')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我希望你能帮助我,谢谢
答案 0 :(得分:0)
模板中的URL反向错误。通过在命名空间中为其指定名称detail
,您需要使用该名称来反转URL,而不是视图的名称。
所以这个:
<a href="{% url 'elements.views.element_detail' pk=el.pk %}">
应该是:
<a href="{% url 'elements.detail' pk=el.pk %}">