user5443740
user5443740

Reputation:

Reverse for 'get_post' with arguments '()' and keyword arguments '{'slug': 'sample-post'}' not found

I am using django 1.9. While implementing class based views and urlpatterns I am not able to redirect my particular link to corresponding post.

settings/urls.py:

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


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^post/', include("posts.urls")),
    url(r'^$', Home.as_view(), name="blog_home"),
]

posts/urls.py

from django.conf.urls import url, include
from .views import Display


urlpatterns = [
    url(r'^(?P<slug>\w+)/$', Display.as_view(), name="get_post"),
]

posts/views.py

class Display(View):
    def get(self, request, slug):
        params = {}
        params['post'] = Post.objects.get(slug=slug)        
        return render(request, "blog/viewpost.html", params)

    def post(self, request):
        pass

and my error follows:

error is shown in that image

Upvotes: 2

Views: 381

Answers (1)

gtlambert
gtlambert

Reputation: 11971

When you use the url regex r'^(?P<slug>\w+)/$, the \w matches alphanumeric characters and underscore. It will not, however, match hyphens -.

So, when your template looks for a URL with slug equal to sample-post, the above regex will not find a match. You should try using this instead:

urlpatterns = [
    url(r'^(?P<slug>[-\w]+)/$', Display.as_view(), name="get_post"),
]

Upvotes: 2

Related Questions