2016-01-23 166 views
0

錯誤模板渲染我不明白這Django的錯誤

在模板中 C:\用戶\稻穀\桌面\ Django的嘖嘖\ mysite的\博客\模板\博客\ post_list.html, 錯誤在第10行反轉'post_detail'參數'()'和 關鍵字參數'{'pk':''}'找不到。 1種模式(S)嘗試: [ '博客/職位/(?P [0-9] +)/ $']

{% extends 'blog/base.html' %} 

{% block content %} 
    <div class="post"> 
     {% if post.published_date %} 
      <div class="date"> 
       {{ post.published_date }} 
      </div> 
     {% endif %} 
     <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1> 

     <!--<h1><a href="">{{ post.title }}</a></h1>--> 

     <p>{{ post.text|linebreaks }}</p> 
    </div> 
{% endblock %} 

post_detail.html文件看起來像這樣

{% extends 'blog/base.html' %} 

{% block content %} 
    <div class="post"> 
     {% if post.published_date %} 
      <div class="date"> 
       {{ post.published_date }} 
      </div> 
     {% endif %} 
     <h1>{{ post.title }}</h1> 
     <p>{{ post.text|linebreaks }}</p> 
    </div> 
{% endblock %} 

urls.py

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

    urlpatterns = [ 
     url(r'^$', views.post_list, name='post_list'), 
     url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), 
    ] 

VIE ws.py

from django.shortcuts import render 
from django.utils import timezone 
from django.shortcuts import render, get_object_or_404 
from .models import Post 
def post_detail(request, pk): 
    post = get_object_or_404(Post, pk=pk) 
    return render(request, 'blog/post_detail.html', {'post': post}) 
    #Post.objects.get(pk=pk) 
# Create your views here. 

def post_list(request): 
    return render(request, 'blog/post_list.html', {}) 

謝謝。

+0

用'post.pk'取代'pk = post.pk' – v1k45

+0

謝謝,但沒有變化。 – Paddy

+0

這應該讓它工作,你確定你在第一個模板中的url標記中替換了它嗎? – v1k45

回答

3

假設您發佈的第一個模板是post_list.html,則不會向其發送任何上下文變量。

post_list視圖 - 如果要列出所有的職位 - 你必須添加:

def post_list(request): 
    posts = Post.objects.all() 
    return render(request, 'blog/post_list.html', {'posts': posts}) 

然後在你的post_list.html模板,你必須遍歷posts

{% extends 'blog/base.html' %} 

{% block content %} 
    {% for post in posts %} # iterate over posts 
    <div class="post"> 
     {% if post.published_date %} 
      <div class="date"> 
       {{ post.published_date }} 
      </div> 
     {% endif %} 
     <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1> 

     <p>{{ post.text|linebreaks }}</p> 
    </div> 
    {% endfor %} 
{% endblock %} 
+0

萬分感謝。 – Paddy

1

當pk爲''(空字符串)時,出現錯誤消息,指出它無法找到反向URL。

確實沒有匹配的URL,因爲正則表達式需要[0-9]+,而且空字符串不匹配。所以不能找到反向匹配。

pk爲空的原因在另一個答案中解釋。