模板渲染时出错?

时间:2015-12-29 23:05:41

标签: python django

我有一个博客应用,这是views.py的相关部分,当然属于博客应用。

from django.conf import settings
from django.shortcuts import render
from .models import Blog

# Create your views here.
def view_homepage(request):
    return render(request, 'index.html', {})

def view_aboutpage(request):
    return render(request, 'about.html', {})

def view_blogpost(request, blog_id):
    article = Blog.objects.get(pk=blog_id)
    return render(request, 'damn.html', {'article':article})

这是博客应用中的urls.py

from django.conf.urls import url, include, patterns
from blog import views

urlpatterns = [
  url(r'^$', views.view_homepage, name=''),
  url(r'about/$', views.view_aboutpage, name='about'),
  url(r'blog/(?P<blog_id>\d+)/$', views.view_blogpost, name='post'),
]

这是项目中的常规urls.py。

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('blog.urls')),
]

这是错误,我有。

NoReverseMatch at /
Reverse for 'post' with arguments '()' and keyword arguments '{}' not found.              1 pattern(s) tried: ['blog/(?P<blog_id>\\d+)/$']
Request Method: GET
Request URL:    http://localhost:8000/
Django Version: 1.9
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'post' with arguments '()' and keyword arguments '{}' not found.     1 pattern(s) tried: ['blog/(?P<blog_id>\\d+)/$']
Exception Location: C:\Users\filip\Python\ENV\lib\site-    packages\django\core\urlresolvers.py in _reverse_with_prefix, line 508
Python Executable:  C:\Users\filip\Python\ENV\Scripts\python.exe
Python Version: 3.5.1

这是html:

<li>
    <a href="{% url "" %}">Home</a>
</li>
<li>
    <a href="{% url "about" %}">About</a>
</li>
<li>
    <a href="{% url "post" article.id %}">Sample Post</a>
</li>
  

反向&#39;发布&#39;参数&#39;()&#39;和关键字参数&#39; {}&#39;未找到。 1种模式尝试过:[&#39;博客/(?P \ d +)/ $&#39;]

1 个答案:

答案 0 :(得分:4)

就像错误所说的那样,你没有一个名为“post”的URL,它没有参数;您调用的URL是期望blog_id参数。所以,你应该在你的标签中传递它;因为你有一个名为article的上下文变量,它将是:

<a href="{% url "post" article.id %}">Sample Post</a>