python - 为什么我在 / 处收到错误 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 %}
解决方案
您还需要在模板中添加 id,详细视图专门寻找一个 id 来显示在 url 和视图中提到但在模板中没有提到的详细视图
<a href="{% url 'blog_post_details' post.id %}">
推荐阅读
- google-cloud-platform - Google Cloud Datastore - 插入一个请求后获取
- python-3.x - 无法使用 Python 和 Cerberus 验证重复值的列表
- dll - VS2019项目在运行时加载一个dll而不是使用静态库
- razor - 链接在本地索引页面上有效,但在部署时无效
- mysql - 命令跟踪用户回滚并查看哪个用户正在提交最大手动回滚
- c# - 如何为 ASP.NET core 2.1 项目启用外部连接?
- mysql - 使用 Tkinter 将文本文件存储到 mysql 中
- android - When using Theme.MaterialComponents the color for + and - in ElegantNumberButton is changing
- r - 在 r 中使用 dplyr 将纯文本转换为数据框
- javascript - 整个网页的平滑滚动