2017-03-04 52 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