找不到带有参数“('',)”的“ edit_post”。尝试了1种模式:['edit_post /(?P <博客ID> \\ d +)/ $']

时间:2019-02-28 15:36:35

标签: python django

enter image description here,blog_post.html正常运行,直到通过“编辑帖子”链接,并产生上述错误;另一方面,如果我从网址格式中删除了“ blog_id”参数,并且“来自“编辑帖子”链接的blog.id”,但是相应地,当我单击“编辑帖子”链接并打开edit_post.html页面时,如果我再次重新传递参数,则它要求缺少(edit_post)参数,则会发生另一个错误那么网址格式不匹配。

from django.conf.urls import url

from . import views

app_name = 'blogs'

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

    #make page for blogposts
    url(r'^blogposts/$',views.blogposts,name='blog_post'),

    #page for making a new post
    url(r'^new_post/$',views.make_post,name='add_post'),

    #page for editing post
    url(r'^edit_post//(?P<blog_id>\d+)$', views.edit_post, name = 'edit_post'),
]

the view page
    from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponseRedirect
from .models import BlogPost
from .forms import BlogPostForm
def edit_post(request,blog_id):
    post = BlogPost.objects.get(id=blog_id)

    if request.method != 'POST':
        form = BlogPostForm(instance = post)
    else:
        form = BlogPostForm(instance = post, data =request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('blogs:blog_post'))
    context = {'post':post,'form':form}
    return render(request,'blogy/edit_post.html',context)



the page of the posts
 {% extends "blogy/base.html" %}

{% block content %}
<p>The Posts:</p>
<ul>
    {% for blog in blogs %}
        <li>
            <p>{{ blog.date_added|date:'M d, Y H:i' }}</p>
            <p>{{ blog.text|linebreaks }}</p>
            <p>
                <a href = "{% url 'blogs:edit_post' %}">edit post</a>
            </p>
        </li>
        {% empty %}
        <li>no posts !</li>
    {% endfor %}
</ul>
<a href="{% url 'blogs:add_post' %}">Add a new Post</a>
{% endblock content %}


the page where the edit post link goes
    {% extends "blogy/base.html" %}

{% block content %}
<p>Edit Post:</p>
<form action = "{% url 'blogs:edit_post' blog.id %}" method = 'post'>
    {% csrf_token %}
    {{ form.as_p }}
    <button name='submit'>Save Changes</button>
</form>
{% endblock content %}

2 个答案:

答案 0 :(得分:1)

问题是您的网址正在等待您传递blog_id变量,但您什么也没有传递。 在这里添加blog.id

<a href = "{% url 'blogs:edit_post' blog_id=blog.id %}">edit post</a>

答案 1 :(得分:0)

好吧,我意识到问题所在,应该传递(post.id)而不传递(blog.id),因为视图函数中变量的名称已从字典“ context”呈现为html页面,名称“ post”而不是“ blog”

相关问题