使用参数'(9,)'和未找到关键字参数'{}来反向'编辑'。尝试过0种模式:[]

时间:2016-09-20 18:27:06

标签: python django django-models django-templates django-views

我在尝试访问django中的编辑链接时遇到错误,我在这里查看了堆栈溢出但我没有找到适用于我的情况的解决方案。

错误: 异常类型:NoReverseMatch 异常值:反向'edit',参数'(9,)'和关键字参数'{}'未找到。 0模式尝试:[]参数'{}'未找到。尝试了0种模式:[]

这是我的urls.py

from django.conf.urls import url, include
from django.contrib import admin
from posts import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^create/$', views.create, name='create'),
    url(r'^(?P<id>\d+)/$', views.show_post, name = 'show_post'),
    url(r'^(?P<id>\d+)/edit/$', views.update_post, name = 'update_post'),
    url(r'^(?P<id>\d+)/delete/$', views.delete_post),
]

views.py

from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, HttpResponseRedirect

from .forms import PostForm
from .models import Post

# Create your views here.

def index(request):
    post_list = Post.objects.order_by('-created_date')[:10]
    context = {'post_list': post_list}
    return render(request, 'index.html', context)

def create(request):
    form = PostForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        #flass messages
        messages.success(request, "Successfully created")
        return HttpResponseRedirect(instance.get_absolute_url())


    context = {
        "form":form,
    }
    return render(request, 'post_form.html', context)   


def show_post(request, id=None):
    instance = get_object_or_404(Post, id=id)
    context = {'instance': instance}
    return render(request, 'show_post.html', context)


def update_post(request, id=None):
    instance = get_object_or_404(Post, id=id)
    form = PostForm(request.POST or None, instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        messages.success(request, "Post updated")
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        "form":form,
        "instance":instance
    }
    return render(request, 'post_form.html', context)


def delete_post(request, id=None):
    instance = get_object_or_404(Post, id=id)
    instance.delete()
    messages.success(request, "Successfully deleted")
    return redirect("posts:index")

show_post.html

{% extends "base.html" %}

<div class="container">
{% block content  %}
    <h1> {{instance.title}} </h1>
    <h3>{{instance.content| linebreaks}} </h3>
    <a href="{% url 'posts:index' %}"> Home</a> | <a href="{{instance.url}}" target="_blank" > visit url</a> | 
    <a href="{% url 'posts:update_post' %}"> Edit</a> 

{% endblock %}

</div>

1 个答案:

答案 0 :(得分:3)

您需要使用命名空间。而不是d,您应该使用'edit'

'posts:edit'取决于您在urls.py中使用的名称。