找不到带有参数 '('',)' 的 'edit_post' 的反向解析。尝试了1个模式:['edit_post/(?P<post_id>\\d+)/$']。

7
我正在学习Django教程,尝试在我的博客应用程序中编辑文章时出现了这个错误。我使用的是Django版本:2.0.6和Python版本:3.6.5。
models.py
from django.db import models

class BlogPost(models.Model):
    title = models.CharField(max_length=100)
    text = models.TextField()

    def __str__(self):
        return self.title

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^new_post/', views.new_post, name='new_post'),
    url(r'^edit_post/(?P<post_id>\d+)/$', views.edit_post, name='edit_post'),
]

一份模板引起了第三行的错误 - edit_post.html。 错误信息突出显示 {% url 'edit_post' post.id %}。
{% block content %}
  <form action="{% url 'edit_post' post.id %}" method='post'>
    {% csrf_token %}
    {{ form.as_p }}
    <button name="submit">save changes</button>
  </form>
{% endblock content %}

一个模板(index.html),带有一个指向edit_post.html的链接。
{% block content %}
  <form action="{% url 'new_post' %}" method='post'>
    {% csrf_token %}
    {{ form.as_p }}
    <button name="submit">Make a new post</button>
  </form>
  <ul>
    {% for post in posts %}
      <li>
        {{ post.id }} - {{ post.title }}
        <p>{{ post.text }}</p>
        <a href="{% url 'edit_post' post.id %}">edit post</a>
      </li>
    {% empty %}
      <li>No posts have been added yet.</li>
    {% endfor %}
  </ul>
{% endblock content %}

views.py

def edit_post(request, post_id):
    post = BlogPost.objects.get(id=post_id)
    text = post.text
    title = post.title
    if request.method != 'POST':
        form = BlogForm(instance=post)
    else:
        form = BlogForm(instance=post, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('index'))
    context = {'title': title, 'text': text, 'form': form}
    return render(request, 'blog/edit_post.html', context)

forms.py

from django import forms
from .models import BlogPost

class BlogForm(forms.ModelForm):
    class Meta:
        model = BlogPost
        fields = ['title', 'text']

问题

当我在首页点击“编辑帖子”链接时,出现了上述错误。使用此方法创建新帖子非常顺利,但编辑无法进行。 我被这个问题困扰着,不知道出了什么问题。

我已经尝试过的

  1. 我尝试用django.urls.path替换django.conf.urls.url以及相应的模式。
  2. 我将一个链接改成了一个按钮。
  3. 我尝试过
  4. 我阅读了StackOverflow上的What is a NoReverseMatch error, and how do I fix it?以及其他我能找到的话题。

感谢您的帮助。提前致谢!

1个回答

7
在你的blog/edit_post.html中,你使用了post.id
<form action="{% url 'edit_post' post.id %}" method='post'>
    ...
</form>

但是在 views.py 中你没有将 post 变量传递给 context 变量。

def edit_post(request, post_id):
    post = BlogPost.objects.get(id=post_id)
    ...

    context = {
              'title': title, 
              'text': text, 
              'form': form,
              'post': post # here
              }
    return render(request, 'blog/edit_post.html', context)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接