wemode wemode - 2 months ago 9
Python Question

Reverse for 'edit' with arguments '(9,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []

I'm getting an error when trying to access edit link in django, i have looked here on stack overflow but i haven't found the solution that works in my case.

ERROR :
Exception Type : NoReverseMatch
Exception Value : Reverse for 'edit' with arguments '(9,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] arguments '{}' not found. 0 pattern(s) tried: []

this is my 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>

Answer

You need to use the namespace. Rather than 'edit', you should use 'posts:edit'.

Or 'posts:update_post' depending which name you're using in urls.py.

Comments