How do you create links using slugfield in Django's standard list class?

How do you create links (i.e. href) using SlugField to output the generic Django ListView class? I can now list all the people in the database using the code below, but I want slug links to display the person's description when clicked.

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>

      

+3


source to share


1 answer


You don't need to do anything in the list view. You need to add the url to urls.py and make a detailed view for your person. Then in the url template link 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 it works here (find the slug).

+1


source







All Articles