在Django泛型listview类中使用slugfield创建链接的方法如下:
from django.db import models
from django.utils.text import slugify
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
from django.urls import path
from .views import ArticleListView
urlpatterns = [
path('articles/<slug:slug>/', ArticleListView.as_view(), name='article-detail'),
]
from django.views.generic import ListView
from .models import Article
class ArticleListView(ListView):
model = Article
template_name = 'article_list.html'
context_object_name = 'articles'
def get_queryset(self):
return Article.objects.all()
{% for article in articles %}
<a href="{% url 'article-detail' slug=article.slug %}">{{ article.title }}</a>
{% endfor %}
这样,你就可以在Django泛型listview类中使用slugfield创建链接了。当用户点击链接时,将会根据slug字段的值来匹配相应的文章详情页。
领取专属 10元无门槛券
手把手带您无忧上云