SlugField中的连字符 [英] Hyphens in SlugField
问题描述
所以,这是一个奇怪的错误,当我打开带有连字符的URL在SlugField,虽然SlugField支持连字符,如文档中所示。错误:
找不到页面(404)
请求方法:GET
请求URL:http: /127.0.0.1:8003/dumpster-rental-prices
使用dumpster.urls中定义的URLconf,Django按以下顺序尝试了这些URL模式:
^ admin /
^(?P< ; slug> \w +)/ $
当前URL,dumpster-rental-prices与这些没有匹配。
如果我将文章的小块更改为dumpster_rental_prices - url 127.0.0.1:8003/dumpster_rental_prices打开
这是博客应用的models.py:
从django.db导入模型
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
这是博客foder中的urls.py:
from django .conf.urls import pattern,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,
t emplate_name ='detail.html')),
)
谢谢提前为您的帮助。
问题是您的正则表达式 - \w
只匹配字母数字字符和下划线。如果你想匹配连字符,你需要像 r'^(?P< slug> [\w - ] +)/ $
的东西。
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.
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.
这篇关于SlugField中的连字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!