Search code examples
pythondjangourlurl-pattern

Django URL Patterns


I've created a very simple blog, but have been running into a couple URL issues. For my tag & specific post views I run into the following issues.

Specific Post View Example
These two sites render the same, and would like the second one to render a 404.
website.com/post/1/hello-world
website.com/post/1/hello-world/non-sense (should render 404)

Tag View
website.com/tag/python: this will render all posts tagged python, great. However...
website.com/tag/python/party: this will render all posts tagged "python/party" instead of rendering a 404.

Here is my URL patterns setup so you can take a look.

url(r'^post/(?P<pk>\d+)/(?P<post_title>)', DetailView.as_view(
                        model = post,
                        template_name = "post.html")),
url(r'^post/$', ListView.as_view(
                        queryset = post.objects.all().order_by("-date"),
                        template_name = "archives.html")),
url(r'^archives/$', ListView.as_view(
                        queryset = post.objects.all().order_by("-date"),
                        template_name = "archives.html")),
url(r'^tag/(?P<tag>[\w|\W]+)', 'tags'),

Updated
Solution for tag:

url(r'^tag/(?P<tag>[\w]+)\W*/$', 'tags'),

Solution for post:

url(r'^post/(?P<pk>\d+)/(?P<post_url>[\w-]+)/$', DetailView.as_view(
                        model = post,
                        template_name = "post.html")),

Thank you Huckleberry Finn and krakax for all the help!


Solution

  • Your post URLconf regex

    url(r'^post/(?P<pk>\d+)/(?P<post_title>)', DetailView.as_view(
                        model = post,
                        template_name = "post.html")),
    

    Should changed to

    url(r'^post/(?P<pk>\d+)/(?P<post_title>[-\w]+)/$', DetailView.as_view(
                        model = post,
                        template_name = "post.html")),
    

    means URLconf is ending with end-slash

    Anyway, Try to define you DetailView URLconf after post ListView. In my opinion if you change your list view and detailview to posts/ and post/ you problem will be solved. The solution is same for tags URLconf issue.