NoReverseMatch at / posts /

时间:2018-03-07 21:58:23

标签: python django exception django-templates django-views

快速信息我是python和django的初学者。

这是一个问题:

我正在尝试使用django创建简单的博客应用程序,我已经创建了所有需要的东西,但是当我尝试访问帖子页面时,我能够呈现我的主要页面之一(以便能够查看当前帖子) )我收到以下错误:

Request Method: GET
Request URL:    http://localhost:8000/posts/
Django Version: 2.0.2
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'post' not found. 'post' is not a valid view function or pattern name.

我不确定为什么我收到此错误,因为我有帖子查看功能已编写和可访问,这是我的文件:

my_blog / urls.py

"""Defines URL patterns for my_blog."""

from django.conf.urls import  url

from . import views

#needed app name
app_name='my_blog'
urlpatterns=[
    #Homepage
    url(r'^$',views.home,name='home'),
    # Show all posts.
    url(r'^posts/$', views.posts, name='posts'),

models.py

from django.db import models

# Create your models here.

class BlogPost(models.Model):
    """Post that can be viewed"""
    title=models.CharField(max_length=200)
    text=models.TextField()
    date_added=models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """Return a string representation of the model."""
        if len(self.text)<50:
            return self.text
        else:
            return self.text[:50] + "..."

views.py

from django.shortcuts import render
from .models import BlogPost
from django.http import HttpResponseRedirect



# Create your views here.

def home(request):
    """The home page for Learning Log"""
    return render(request,'my_blog/home.html')


def posts (request):
    """Show all posts."""
    posts=BlogPost.objects.order_by('date_added')
    context={'posts':posts}
    return  render(request, 'my_blog/posts.html', context)

HTML网页:

home.html的

{%extends "my_blog/base.html"%}

{%block content%}
<html>
<p align="center">Welcome to my Blog</p>

</body>
</html>

{%endblock content%}

base.html文件

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>My Blog</title>
</head>
<body bgcolor="#85C1E9">
<p>
    <a href="{%url 'my_blog:home'%}">Home</a> -
    <a href="{%url 'my_blog:posts'%}">Posts</a>
</p>

{%block content%}{%endblock content%}

</body>
</html>

posts.html

{%extends "my_blog/base.html"%}


{%block content%}

<p>Posts</p>

<ul>
    {%for post in posts%}
    <li><a href="{%url 'my_blog:post' post.id%}">{{post}}</a> </li>
    {%empty%}
        <li>No posts have been added yet.</li>
    {%endfor%}
</ul>
{%endblock content%}

提前感谢您的帮助

2 个答案:

答案 0 :(得分:3)

在您的模板中,您有:

{% url 'my_blog:post' post.id %}

这会产生错误,因为您尚未使用my_blog/urls.pyname="post"中定义网址格式。

答案 1 :(得分:1)

您在模板中查找的视图名称与urls.py中定义的名称不匹配。你需要做

<强> urls.py

    url(r'^posts/$', views.posts, name='posts'),

和 的 posts.html

<li><a href="{%url 'my_blog:post' post.id%}">{{post}}</a> </li>

通过在s中添加posts,html或删除s中的urls.py进行匹配

修改

更深入一点......您需要在post中定义详细视图(views.py带参数)。并在urls.py中添加相应的条目然后撤消我之前建议的更改。

您还应考虑将视图从postspost重命名为post_listpost_detail