django - 如何在 django url 中使用 slugs
问题描述
一直害怕在这里问这个问题,刚从 Stack Overflow 开始,相信我,我已经尝试过搜索这个问题,但大多数情况下我看到了正则表达式模式。
请如果有人可以指导我解决这些问题:
如何使用帖子名称自动填充我的博客模型 slug 字段,而无需自己填写。
如何在 Django 2.x 中使用没有正则表达式的 slug 建立一个链接以转到单个帖子页面
谢谢。
解决方案
所以你还没有发布你的代码,但假设你的模型看起来像这样:
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
content = models.TextField()
并且您想从标题中预先填写slug
,您有几个选项,具体取决于您要在哪里做:
Post
将仅由员工用户创建:在管理员中预填充Post
将在管理员之外创建:覆盖.save()
方法
从管理员
在管理员中获取此信息的最简单方法是通过prepopulated_fields
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
当您在创建帖子时键入标题时, Django 将自动更新 slug 字段。非常好的用户体验,但仅限于管理员......
管理员之外
在前面的示例中,如果您要从控制台或其他页面创建帖子,最终可能会得到一个空 slug。.save()
在这种情况下,您可以通过覆盖模型的方法并调用它来快速确保预填充 slug slugify
:
class Post(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
content = models.TextField()
def save(self, *args, **kwargs):
self.slug = self.slug or slugify(self.title)
super().save(*args, **kwargs)
链接 slug 发帖
免责声明:如果您需要有关这部分的更多详细信息,我建议您阅读官方教程的第 3 部分。
如果您有 URL 路径:
# urls.py
from django.urls import path
from your_blog import views
urlpatterns = [
path('posts/<slug:the_slug>/', views.post_detail_view, name='show_post'),
]
然后,在您的视图模块中,您有一个视图:
# your_blog/views.py
from django.views.generic.detail import DetailView
class PostDetailView(DetailView):
model = Post
# This file should exist somewhere to render your page
template_name = 'your_blog/show_post.html'
# Should match the value after ':' from url <slug:the_slug>
slug_url_kwarg = 'the_slug'
# Should match the name of the slug field on the model
slug_field = 'slug' # DetailView's default value: optional
post_detail_view = PostDetailView.as_view()
Post
您可以在 Python 中通过调用链接到 a :
reverse('show_post', args=[the_post.slug])
或者在 Django 模板中:
<a href="{% url 'show_post' the_post.slug %}">{{ the_post.title }}</a>
编辑:发布索引页面
然后,您可以添加一个索引页面,生成一个链接到您所有帖子的列表:
# your_blog/views.py
from django.views.generic import ListView
class PostListView(ListView):
model = Post
# This file should exist somewhere to render your page
template_name = 'your_blog/list_post.html'
在视图模板中:
<!-- your_blog/list_post.html -->
<ul>
{% for the_post in object_list %}
<li>
<a href="{% url 'show_post' the_post.slug %}">{{ the_post.title }}</a>
</li>
{% endfor %}
</ul>
希望有帮助:)
推荐阅读
- azure - DocumentFormat.openxml 似乎不适用于 Azure 函数
- javascript - 将字符串格式数组加载到数组中
- html - ERR_NAME_NOT_RESOLVED 使用 fontawesome
- flutter - Flutter升级后未配置Dart SDK
- lcov - 如何在运行 lcov 程序的同时生成代码覆盖率
- javascript - 我如何在 javascript 中创建一个 objectArray 以根据另一个下拉列表获取下拉列表的值
- php - 我在 Laravel 中的搜索表单中的过滤器问题
- regex - 如何在python中使用正则表达式正确匹配序列?
- r - 如何通过系统地重新排列现有 data.frames 列表中的列来创建新的 data.frames 列表
- python - 从 pandas 数据框中的特定过滤列集中删除空列