SlugField中的连字符

时间:2012-04-20 20:34:45

标签: django django-models django-views slug hyphen

当我在slug中打开带有连字符的URL时出现一个奇怪的错误,尽管SlugField支持连字符,如文档中所示。

所以,这是错误:

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.

如果我将文章的slug更改为dumpster_rental_prices - 网址127.0.0.1:8003/dumpster_rental_prices打开正常。

这是博客应用的models.py:

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

这是博客中的urls.py:

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')),    

)

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:6)

问题在于你的正则表达式 - \w只匹配字母数字字符和下划线。如果你想匹配连字符,你需要像r'^(?P<slug>[\w-]+)/$这样的东西。