模板渲染期间Django NoReverseMatch错误

时间:2020-07-28 18:40:45

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

我正在使用Django建立一个简单的博客网站,并在尝试链接到允许用户编辑现有博客文章的页面时遇到此错误。

Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_post/(?P<title_id>[0-9]+)/$']

如果我正确理解此错误,则意味着Django无法找到与所请求网址匹配的urlpattern。在我看来,我已经正确设置了urlpattern,但是仍然出现错误。

有问题的链接显示在text.html模板上,该模板是显示特定博客文章文本的模板。

以下是相关代码:

urls.py

"""Defines URL patterns for blogs."""

from django.urls import path

from . import views

app_name = 'blogs'
urlpatterns = [
    # Home page, shows all posts in chronological order.
    path('', views.index, name='index'),
    # A page to show the text of a specific post.
    path('text/<int:title_id>/', views.text, name='text'),
    # Page for adding a new post.
    path('new_post/', views.new_post, name='new_post'),
    # Page for editing a post.
    path('edit_post/<int:title_id>/', views.edit_post, name='edit_post'),
]

views.py

from django.shortcuts import render, redirect

from .models import BlogPost 
from .forms import BlogPostForm

def index(request):
    """The home page for blogs, shows all posts."""
    titles = BlogPost.objects.order_by('date_added')
    context = {'titles': titles}
    return render(request, 'blogs/index.html', context)

def text(request, title_id):
    """Show a single post title and its text."""
    title = BlogPost.objects.get(id=title_id)
    text = title.text
    context = {'title': title, 'text': text}
    return render(request, 'blogs/text.html', context)

def new_post(request):
    """Add a new post."""
    if request.method != 'POST':
        # No data submitted; create a new form.
        form = BlogPostForm()
    else:
        # POST data submitted; process data.
        form = BlogPostForm(data=request.POST)
        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.save()
            return redirect('blogs:index')

    # Display a blank or invalid form.
    context = {'form': form}
    return render(request, 'blogs/new_post.html', context)

def edit_post(request, title_id):
    """Edit an existing post."""
    post = BlogPost.objects.get(id=title_id)

    if request.method != 'POST':
        # Initial request: pre-fill form with the current post.
        form = BlogPostForm(instance=post)
    else:
        # Post data submitted; process data.
        form = BlogPostForm(instance=post, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('blogs:index')

    context = {'post': post, 'form': form}
    return render(request, 'blogs/edit_post.html', context)

index.html(这是博客的首页)

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

{% block content %}
<p>Blog is a generic site for a blogger to post content for their audience.</p>

    <p>Posts</p>

    <ul>
        {% for title in titles %}
            <li>
                <a href="{% url 'blogs:text' title.id %}">{{ title }}</a>
            </li>
        {% empty %}
            <li>No posts have been added yet.</li>
        {% endfor %}
    </ul>

    <a href="{% url 'blogs:new_post' %}">Create a new post</a>

{% endblock content %}

text.html(此页面显示特定帖子的文本内容以及编辑帖子的链接)

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

{% block content %}

    <p>Title: {{ title }}</p>

    <p>{{ text }}</p>

    <a href="{% url 'blogs:edit_post' title.id %}">Edit post</a>

{% endblock content %}

edit_post.html(此页面应显示现有帖子并允许对其进行编辑)

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

{% block content %}
    
    <p>Edit post:</p>

    <p>Title:</p>

    <form action="{% url 'blogs:edit_post' title.id %}" method='post'>
        {% csrf_token %}
        {{ form.as_p }}
        <button name="submit">Save changes</button>
    </form>

{% endblock content %}

views.py中的edit_post函数应该如何工作(理论上)是根据帖子的标题ID创建一个实例,然后允许用户对其进行编辑并保存更改。

我不确定我在哪里出错了,任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您传递给模板的帖子对象的名称不是 title ,而是post

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

{% block content %}
    
    <p>Edit post:</p>

    <p>Title:</p>

    <form action="{% url 'blogs:edit_post' post.pk %}" method='post'>
        {% csrf_token %}
        {{ form.as_p }}
        <button name="submit">Save changes</button>
    </form>

{% endblock content %}

如果使用title.id,它将找不到该变量,因此将解析为空字符串。如果您使用post.idpost.pk,它将解析为.id字段或post对象的主键。