如何使用SlugField为Django的ListView泛型类的输出创建链接(即href)?现在我可以使用下面的代码列出数据库中的所有人员,但我想要点击时使用slug链接将显示该人的描述。
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 }} {{ person.last_name }}</li>
{% endfor %}
</ul>
答案 0 :(得分:1)
您无需在列表视图中执行任何操作。您需要将URL添加到urls.py并为您的人员创建详细信息视图。然后在模板中引用url并传递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 }} {{ person.last_name }}</a></li>
{% endfor %}
</ul>
了解其原因here(寻找slug)。