3

How to you create links (i.e. href) using SlugField for the output of Django's ListView generic class? Right now I can list all persons in the database using the code below but I want links using slug when clicked will show the person's description.

models.py
class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    slug = models.SlugField(max_length=50)
    description = models.TextField()

views.py
class PersonList(ListView):
    model = Person 

person_list.html
<ul>
{% for person in object_list %}
    <li>{{ person.first_name }}&nbsp{{ person.last_name }}</li>
{% endfor %}
</ul>
cw12345
  • 383
  • 1
  • 2
  • 9

1 Answers1

2

You don't have to do anything in the list view. You need to add the URL to urls.py and make a detail view for your person. Then in the template reference the url and pass the slug:

app/urls.py:

from . import views

urlpatterns = [
    # ... other urls
    url(
        r'^person/(?P<slug>[a-z0-9-]+)$',  # Match this
        views.PersonDetailView.as_view(),  # Call this view
        name='person_detail'  # Name to use in template
   )
]

app/views.py:

from django.views import generic
from .models import Person

class PersonDetailView(generic.DetailView):
    model = Person

app/templates/app/person_list.html:

<ul>
    {% for person in object_list %}
        <li><a href="{% url 'person_detail' slug=person.slug %}">{{ person.first_name }}&nbsp{{ person.last_name }}</a></li>
    {% endfor %}
</ul>

See why this works here (look for slug).

  • Thanks for clear answer! What about doing it in listview? could you please add it as well? – Ulvi Sep 14 '20 at 18:26