2017-03-04 29 views
0

我得到一个NoReverse匹配错误。我已经阅读了几篇关于这个问题的文章以找到答案,但我没有看到解决方案。NoReverseMatch在/

这是一个简单的博客webapp,用于按时间顺序显示帖子。该错误与“views.py”中的edit_post函数有关。我的怀疑是,错误与尝试将posts.id作为参数存储在修改帖子时有关。我尝试删除下面的攻击行中的post.id,它会加载页面。问题是,如果我这样做,我无法加载页面编辑特定的职位后。

我不明白我错过了什么。我查看了一些处理这个错误的帖子,并且我无法确定我的特定场景的问题。很感谢任何形式的帮助。

我的错误:

NoReverseMatch at /

Reverse for 'edit_posts' with arguments '('',)' and keyword arguments '{}' >not found. 1 pattern(s) tried: ['edit_posts(?P\d+)/']

这里是在主页的违规行 “的index.html”:

<p> 
<a href="{% url 'blogs:edit_posts' posts.id %}">edit post</a> 
</p> 

索引视图:

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

我“的网址.py“:

urlpatterns = [ 
    # Home page 
    url(r'^$', views.index, name='index'), 
    # url(r'^posts/$', views.posts, name='posts'), 

    # Page for adding a new post. 
    url(r'^new_post/$', views.new_post, name='new_post'), 

    # Page for editing posts. 
    url(r'^edit_posts(?P<posts_id>\d+)/$', views.edit_posts, 
     name='edit_posts'), 
] 

edit_posts查看:

def edit_posts(request, posts_id): 
    """Edit an existing post.""" 
    posts = BlogPost.objects.get(id=posts_id) 

    if request.method != 'POST': 
     # Initial request; pre-fill form with the current entry. 
     form = PostForm(instance=posts) 
    else: 
     # POST data submitted; process data. 
     form = PostForm(instance=posts, data=request.POST) 
     if form.is_valid(): 
      form.save() 
      return HttpResponseRedirect(reverse('blogs:index', 
              args=[posts.id])) 

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

为 “edit_posts.html” 页面模板:

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

{% block content %} 

    <p>Edit an existing post:</p> 

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

{% endblock content %} 
+0

哪里是呈现指数为索引视图代码.html,因为那是错误发生的地方? –

+0

我会发布回溯,但经过多次尝试,我遇到了错误。如果有人认为有必要,我会再试一次。 – gjw227

+0

已添加索引视图。 – gjw227

回答

0

在你的模板,posts - 顾名思义 - 是一个QuerySet,即博文列表对象。该查询集没有id属性;只有该列表中的各个职位才会这样做。

如果你要链接到一个特定的职位,你需要遍历该列表,并使用循环每个帖子的id

{% for post in posts %} 
<p> 
<a href="{% url 'blogs:edit_posts' post.id %}">edit post</a> 
</p> 
{% endfor %} 
+0

感谢您提供快速有效的反馈。这解决了它。 – gjw227