我不明白这个Django错误

时间:2016-01-23 06:45:39

标签: python django

模板渲染期间出错

  

在模板中   C:\用户\稻谷\桌面\ Django的啧啧\ mysite的\博客\模板\博客\ post_list.html,   第10行的错误反向' post_detail'参数'()'和   关键字参数' {' pk':''}'未找到。尝试过1种模式:   ['博客/后/ / $&#39(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'),
    ]

views.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', {})

感谢。

2 个答案:

答案 0 :(得分: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 %}

答案 1 :(得分:1)

出现错误消息时,如果pk为''(空字符串),则无法找到反向网址。

确实没有与之匹配的网址,因为正则表达式需要[0-9]+,而空字符串与之匹配。因此无法找到反向匹配。

另一个答案解释了pk为空的原因。