SlugField中的连字符

编程入门 行业动态 更新时间:2024-10-12 12:23:38
本文介绍了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: 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中的连字符

本文发布于:2023-11-29 13:43:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646547.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   SlugField

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!