0

当我在 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 - url 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')),    

)

预先感谢您的帮助。

4

1 回答 1

6

问题是您的正则表达式 -\w仅匹配字母数字字符和下划线。r'^(?P<slug>[\w-]+)/$如果您还想匹配连字符,则需要类似的东西。

于 2012-04-20T20:47:21.107 回答