模型.py
class Tag(models.Model):
name = models.CharField(max_length=64, unique=True)
slug = models.SlugField(max_length=255, unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Tag, self).save(*args, **kwargs)
urls.py
url(r'^tag/(?P<slug>[A-Za-z0-9_\-]+)/$',
TagDetailView.as_view(),
name='tag_detail'),
View .py
class TagDetailView(DetailView):
model = Tag
template_name = 'tag_detail_page.html'
context_object_name = 'tag'
这给了我一个 404:
Page not found (404)
http://localhost:9999/tag/RandomTag/
No tag found matching the query
为什么 Django 无法根据 slug 字段获取正确的对象?
最佳答案
Django 的 slugify
方法:
Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace.
您正在寻找 Camel Case 的标签:
http://localhost:9999/tag/RandomTag/
你需要使用小写:
http://localhost:9999/tag/randomtag/ # or `random-tag` depending on the name
检查您的数据库以确切了解
slug
已保存
关于Django DetailView 找不到基于 SLUG 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18250821/