Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django reverse error: NoReverseMatch

Tags:

I've looked at a lot of different posts, but they're all either working with a different version of django or don't seem to work. Here is what I'm trying to do:

urls.py (for the entire project):

    from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
        url(r'^blog/', include('blog.urls', namespace="blog")),
        url(r'^admin/', include(admin.site.urls)),
    )

urls.py (specific to the app):

urlpatterns = patterns ('' ,
url(r'^$', views.index, name='index'),

url(r'^(?P<slug>[\w\-]+)/$', views.posts, name="postdetail"),

)

views.py:

def index(request):
    posts = Post.objects.filter(published=True)
    return render(request,'blog/index.html',{'posts':posts})

def posts(request, slug):
    post = get_object_or_404(Post,slug=slug)
    return render(request, 'blog/post.html',{'post':post})

And finally the template:

 {% block title %} Blog Archive {% endblock %}

    {% block content %}
        <h1> My Blog Archive </h1>
        {% for post in posts %}
        <div class="post">
            <h2>
                <a href="{% url "postdetail" slug=post.slug %}">
                    {{post.title}}
                </a>
            </h2>
            <p>{{post.description}}</p>
            <p>
                Posted on
                <time datetime="{{post.created|date:"c"}}">
                    {{post.created|date}}
                </time>
            </p>
        </div>
        {% endfor %}
    {% endblock %}

For some reason this gives me a "No reverse Match": Reverse for 'postdetail' with arguments '()' and keyword arguments '{u'slug': u'third'}' not found. 0 pattern(s) tried: []

I've already tried getting rid of the double quotes around postdetail in the template, and I've also tried referring to it by the view name instead of the pattern name. Still no luck. The documentation isn't too helpful either.

Help is really appreciated! Thanks

like image 429
Sid Avatar asked Jan 02 '14 18:01

Sid


People also ask

What is NoReverseMatch error in Django?

NoReverseMatch (source code) is a Django exception that is raised when a URL cannot be matched against any string or regular express in your URL configuration. A URL matching problem is often caused by missing arguments or supplying too many arguments.

How do I reverse in Django?

reverse() If you need to use something similar to the url template tag in your code, Django provides the following function: reverse (viewname, urlconf=None, args=None, kwargs=None, current_app=None)


1 Answers

You've used a namespace when including the URLs, so you probably need to use "blog:postdetail" to reverse it.

like image 145
Daniel Roseman Avatar answered Oct 04 '22 23:10

Daniel Roseman