-1

If you have a blog model in Django that saves a slug, how do you create an href link from that slug field?

Bootstrap4
  • 3,671
  • 4
  • 13
  • 17

1 Answers1

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