Hyphens in SlugField

自闭症网瘾萝莉.ら 提交于 2019-12-25 08:16:04

问题


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:


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.



来源:https://stackoverflow.com/questions/10253200/hyphens-in-slugfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!