If you have a blog model in Django that saves a slug, how do you create an href link from that slug field?
Asked
Active
Viewed 960 times
-1
-
1in template: `{{post.title}}` in urls.py: `url(r'^(?P
[\w-]+)/', views.something, name='post'),` – hansTheFranz Jun 20 '17 at 00:23
1 Answers
0
You should create a view according to Django MVT architecture.
For example you can create a DetailView and associate it with an URL.
# views.py
from django.views.generic.detail import DetailView
from someapp.models import SomeModel
class SomeModelDetailView(DetailView):
model = SomeModel
# urls.py
from django.conf.urls import url
from someapp.views import SomeModelDetailView
urlpatterns = [
url(r'^(?P<slug>[-\w]+)/$', SomeModelDetailView.as_view(), name='somemodel-detail'),
]
And just use the {% url %}
template tag to access to this page. For example :
<a href="{% url 'somemodel-detail' foo.slug %}">{{ foo.name }}</a>
Where foo
is a SomeModel
instance.

Augustin Laville
- 476
- 5
- 14