Charles Smith
Charles Smith

Reputation: 3289

Django NoReverseMatch on post_edit URL

I added an edit view to my blog so my assistant can edit from the front-end and not the admin area. I have the post_edit URL setup identical to my post_detail with the exception of an /edit/ attribute at the end. When I am reviewing a post and I manually add the /edit/ to the end of the URL, it works great, but I am having an issue created an edit button and passing parameters.

This is the browser error:

NoReverseMatch at /press/2016/05/23/gdfgdfcdcd/ Reverse for 'post_edit' with arguments '(2016, 5, 23, 'gdfgdfcdcd')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['press/(?P\d{4})/(?P\d{2})/(?P\d{2})/(?P[-\w]+)/edit/$']

Thank you for looking.

url

urlpatterns = [
    ...
    url(r'^press/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'),
    url(r'^press/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/edit/$', views.post_edit, name='post_edit'),
    ...
]

view

def post_edit(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post, status='published', created__year=year, created__month=month, created__day=day)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            form.save()
            form.save_m2m()
            return HttpResponseRedirect(post.get_absolute_url())
    else:
        form = PostForm(instance=post)
    return render(request, 'press/post_edit.html', {'post': post, 'form': form})

template

<a href="{% url 'press:post_edit' post.created.year post.created.month post.created.day post.slug %}"><i class="fa fa-envelope-o" aria-hidden="true"></i> Edit Post</a>

Upvotes: 0

Views: 139

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599628

Your regex does not match because it is expecting exactly 2 digits for the month, but you are only passing one ('5'). You should ensure that both the month and day parameters accept either one or two digits.

r'^press/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})...

Upvotes: 1

ddalu5
ddalu5

Reputation: 401

In the urls you did put {2} for day and month parameters which means that you need them each to be two decimal characters exactly to be valid which is incorrect, so better change it to {1,2}:

urlpatterns = [
    ...
    url(r'^press/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'),
    url(r'^press/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<post>[-\w]+)/edit/$', views.post_edit, name='post_edit'),
    ...
]

Upvotes: 1

Related Questions