2👍
In your template, assuming post
is an instance of your model:
{% url single_post post.slug %}
Your url regex should look like the following:
url(r'^post/(?P<slug>[\w-]+)/$', ...
To test the above regex, try to access a few posts directly in your browser with a variety of valid slugs and see if they works. Once this is done, start testing the url names.
- [Django]-Django Templates – how do I output the relative path of file when using a FilePathField recursively
- [Django]-Django Model API reverse lookup of many to many relationship through intermediary table
- [Django]-Django official tutorial for the absolute beginner, absolutely failed!
2👍
A slug value can contain any a-z
, A-Z
, 0-9
, _
and -
. The first 3 are represented by the special character w
and since -
itself is a special character, we need to use represent them both using a backslash \
. So the correct expression becomes
url(r'^post/(?P<slug>[\w\-]+)/$', ...
At least this is what is working in my case.
- [Django]-Changing package install order in Python
- [Django]-Django shell doesn't respect cache configuration
- [Django]-Django trigger post_save on update()
- [Django]-Django Administration: Delete record from custom user model
2👍
In Django 1.5 the slug validator uses this regex:
slug_re = re.compile(r'^[-a-zA-Z0-9_]+$')
See https://github.com/django/django/blob/stable/1.5.x/django/core/validators.py#L106
You can use this regex in urls.py:
url(r'^post/(?P<slug>[-a-zA-Z0-9_]+)/$', ...
In earlier versions it was [-\w]+
but I guess in Python3 \w matches non ascii characters like umlauts.
- [Django]-How to make Router display urls from Multiple apps in Browsable API root view in Django REST Framework?
- [Django]-Django – Redirect user to "next" parameter after successful login
- [Django]-Facebook Connect API error 191 with Django-socialregistration
- [Django]-Django sites framework and Heroku
- [Django]-How to set PYTHONPATH on web server