Using Slugify in Django urls

扶醉桌前 提交于 2019-12-06 10:44:43

You're trying to request an object with its slug instead of its name in database. The slug is a string, compute from the original name, which you can use in URL (because it's SEO-friendly). But you can't request objects with it if you don't have save this slug anywhere in your database. Indeed, it's impossible to retrieve the original name from the slug.

Above & Beyond --> above-beyond --> Above @ Beyond  }
                                --> above & beyond  } A lot of possibilities...
                                --> ABOVE - BEYOND  } 
                                --> ...

You need to use a SlugField() and get the object wanted according to this new field. Short example:

class News(models.Model):
    title = models.CharField('title', max_length=100)
    slug = models.SlugField('slug', max_length=100, unique=True)
    content = models.TextField('news content')

    def get_absolute_url(self):
        return reverse('news-view', args=(self.slug, ))

# In the app/urls.py:
from . import views
urlpatterns = [
    url(r'^(?P<slug>.+)/$', view.news_detail, name='news-view'),
    #...
]

# In the 'news_detail' view (app/views.py)
news = get_object_or_404(News, slug=slug)

In practice, you can use the templatetags slugify if you want to use clean URL like stackoverflow: they're using the ID of the question to retrieve the content from the URL, but there's also the title, which you can change, it'll redirect you anyway.

http://stackoverflow.com/questions/21377984/using-slugify-in-django-urls
                                   ^^^^^^^^
                                   ID used  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                            slug just for SEO purpose, not
                                            used to retrieve from the db

why don't you use SlugField() in your models ? Then you can queryset on your slug. I guess the error comes from the queryset on name instead of a slug.

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