1
我試圖訪問Django中的編輯鏈接時出現錯誤,我在這裏看到堆棧溢出,但我還沒有找到解決方案,在我的情況下工作。未找到參數'(9,)'和關鍵字參數'{}'的'編輯'反向。 0模式嘗試:[]
錯誤: 異常類型:NoReverseMatch 異常值:未找到參數'(9,)'和關鍵字參數'{}'的'編輯'反向。嘗試了0個模式:[] arguments'{}'not found。 0模式(S)嘗試:[]
這是我的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>
你的'urls.py'沒有'name ='edit''的url。 –
我將name從'name ='update_post'更改爲name ='edit',但仍然出現錯誤。 – helloworld
@wemode你需要做相反的事情,只要'urls.py'和'show_post.html'同意網址名稱,就可以在_show_post.html_ –