Hyphens in SlugField

2019-08-17 18:37发布

There is a strange error when i open a URL with hyphens in the slug, though SlugField supports hyphens in it as indicated in documentation.

So, this is the error:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8003/dumpster-rental-prices
Using the URLconf defined in dumpster.urls, Django tried these URL patterns, in this order:
^admin/
^(?P<slug>\w+)/$
The current URL, dumpster-rental-prices, didn't match any of these.

If i change the slug of the article to dumpster_rental_prices - the url 127.0.0.1:8003/dumpster_rental_prices opens fine.

This is models.py of blog app:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length = 100)
    body = models.TextField(max_length = 5000)
    slug = models.SlugField(max_length = 100)

    def __unicode__(self):
        return self.title

This is urls.py in blog foder:

from django.conf.urls import patterns, include, url
from django.views.generic import DetailView, ListView
from blog.models import Post

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^(?P<slug>\w+)/$',
        DetailView.as_view(
            model=Post,
            template_name='detail.html')),    

)

Thank you in advance for your help.

1条回答
做个烂人
2楼-- · 2019-08-17 19:00

The problem is your regex - \w only matches alphanumerical characters and underscores. You need something like r'^(?P<slug>[\w-]+)/$ if you want to match hyphens as well.

查看更多
登录 后发表回答