【问题标题】:NoReverseMatch at /posts//posts/ 处的 NoReverseMatch
【发布时间】:2018-03-07 21:58:22
【问题描述】:

快速信息我是 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%}

提前感谢您的帮助

【问题讨论】:

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


    【解决方案1】:

    在您的模板中,您有:

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

    这会产生错误,因为您尚未在 my_blog/urls.py 中使用 name="post" 定义 URL 模式。

    【讨论】:

      【解决方案2】:

      您在模板中查找的视图名称与 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>
      

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

      编辑

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

      您还应该考虑将视图从postspost 重命名为post_listpost_detail 之类的名称

      【讨论】:

      • 谢谢@Alan,我按照你的建议做了,现在我有了这个:Reverse for 'posts' with arguments '(1,)' not found。尝试了 1 种模式:['posts/$']
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2018-12-09
      • 2020-10-28
      • 2020-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多