首页 > 解决方案 > 为什么我在 / 处收到错误 NoReverseMatch?

问题描述

我正在尝试在 django 上建立一个博客站点。我是初学者,不知道为什么会出现这个错误。请帮我解决这个错误。我正在提供我的代码views.py、models.py 和base.html 文件

#models.py
from django.db import models
from django.urls import reverse


class Post(models.Model):
    author = models.ForeignKey(
        'auth.User',
        on_delete = models.CASCADE,
        null = True
        )
    title = models.CharField(max_length = 20, default='')
    text = models.TextField()


    def __str__(self):
        return self.title

    def get_absolute_url(self): # new
        return reverse('blog_post_details', args=[str(self.id)])

视图.py

from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView

from .models import Post

class HomeResponse(ListView):
        model = Post
        template_name = 'home.html'

class PostDetail(DetailView):
    """docstring for PostDetail"""
    model = Post
    template_name = 'post_detail.html'



class NewPost(CreateView):
        model = Post
        template_name = 'new_post.html'
        fields = '__all__'

这是我的 urls.py 代码

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('', views.HomeResponse.as_view(), name='blog_name'),
    path('post/new/', views.NewPost.as_view(), name='blog_new_post'),
    path('post/<int:pk>/',views.PostDetail.as_view(),name='blog_post_details'),
]

base.html 浏览器显示此代码错误。它说Reverse for 'blog_post_details' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$']

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <header>
        <h1>Django Blog</h1>
        <h4 style="float: right;"><a href="{% url 'blog_new_post' %}">+ New Post</a></h4>
        <hr>
    </header>
    <a href="{% url 'blog_name' %}">Home</a>
    <a href="#"></a>

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

</body>
</html>


{% extends 'base.html' %}

这是带有 blog_post_details 链接 {% block content %} 的模板

    {% for post in object_list %}

            <fieldset><a href="{% url 'blog_post_details' %}">
                <h1>{{ post.title }}</h1>
                <p style="font-size: 20px;">{{ post.text }}</p>
                <h4>By: {{ post.author }}</h4></a>
            </fieldset>
    {% endfor %}
{% endblock content %}

标签: pythondjango

解决方案


您还需要在模板中添加 id,详细视图专门寻找一个 id 来显示在 url 和视图中提到但在模板中没有提到的详细视图

<a href="{% url 'blog_post_details' post.id %}">

推荐阅读