我正在尝试编辑现有帖子并将其保存到数据库但没有反向匹配错误。下面是我的代码

时间:2018-01-11 04:06:23

标签: python django

urls.py文件。

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

app_name = 'posts'

urlpatterns = [
    url(r'^create/', views.create, name='create'),
    url(r'^(?P<pk>[0-9]+)/upvote', views.upvote, name='upvote'),
    url(r'^(?P<pk>[0-9]+)/downvote', views.downvote, name='downvote'),
    url(r'^user/(?P<pk>[0-9]+)', views.user_post, name='user_post'),
    url(r"^delete/(?P<pk>[0-9]+)", views.delete_post, name="delete"),
    url(r"^edit/(?P<pk>[0-9]+)", views.edit_post, name="edit"),
    url(r"^save_post/(?P<pk>[0-9]+)", views.save_post, name="save_post"),
]

views.py文件。编辑后保存帖子的功能

def save_post(request,pk):
    if request.method == 'POST':
        post = Post.objects.get(pk=pk)

        post.title = request.POST['title']

        if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
            post.url = request.POST['url']
        else:
            post.url = "http://" + request.POST['url']

        post.save()
        return redirect('home')

    else:
        return render(request,'posts/edit_post.html')

edit_post.html文件。 html文件,其中将提取现有数据,用户可以编辑

{% extends 'base.html' %}

{% block body_block %}
  <div class="jumbotron">
    <h3>Edit Post</h3>

      <form method="POST">

        {% csrf_token %}
          <div class="form-group form-group-md">
            <label for="title">Title</label>
            <input class="form-control" id="title" name="title" type="text" value="{{post.title}}">

            <label for="url">URL</label>
            <input class="form-control" id="url" name="url" type="text" value="{{post.url}}">
          </div>
          <a href="{% url 'posts:save_post' %}" class="btn btn-md btn-success">Save</a>
      </form>
  </div>
{% endblock %}

when going to save, getting following error

2 个答案:

答案 0 :(得分:0)

您需要在网址中传递ID

{% extends 'base.html' %}

{% block body_block %}
  <div class="jumbotron">
    <h3>Edit Post</h3>

      <form method="POST" action="{% url 'posts:save_post' post.id %}">

        {% csrf_token %}
          <div class="form-group form-group-md">
            <label for="title">Title</label>
            <input class="form-control" id="title" name="title" type="text" value="{{post.title}}">

            <label for="url">URL</label>
            <input class="form-control" id="url" name="url" type="text" value="{{post.url}}">
          </div>
          <input type="submit" class="btn btn-md btn-success" value="Save" />
      </form>
  </div>
{% endblock %}

答案 1 :(得分:0)

您未将post传递到GET请求的上下文中,这就是您获得NoReverseMatch

的原因

e.g。而不是

 return render(request,'posts/edit_post.html')

return render(request,'posts/edit_post.html', { "post": post } )

(当然,您还需要将post = Post.objects.get(pk=pk)移到第一个if之上