重写规则Django,以u显示h1文本

2024-06-17 12:12:51 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的文章 url.py

app_name = 'articles'
urlpatterns = [
    url(r'^(?P<article_id>[0-9]+)/$', views.detail, name='detail'),
]

还有我的文章models.py

class Article(models.Model):
    heading_text = models.CharField(max_length=150)

我可以通过以下链接访问文章:www.example.com/articles/7/ 但我希望用户在他的url中看到文章的标题文本,例如:www.example.com/articles/how-to-do-this 或者如果有必要,在url中保留标题文本和文章id:www.example.com/articles/7/how-to-do-this . 我怎样才能做到这一点


Tags: tonamepy文本comidurl标题
1条回答
网友
1楼 · 发布于 2024-06-17 12:12:51

你想要的东西叫做slughttps://docs.djangoproject.com/en/1.11/ref/models/fields/#slugfield

但是为了简化这个过程,我建议你像那样使用django-autoslughttps://github.com/neithere/django-autoslug/

from autoslug import AutoSlugField

class Article(models.Model):
    heading_text = models.CharField(max_length=150)
    slug = AutoSlugField(populate_from='heading_text')

在这种情况下,每次保存时,slug都会自动更新并检查其唯一性

现在,为了让它工作,你需要稍微改变一下你的urls.py

app_name = 'articles'

urlpatterns = [
    url(r'^(?P<slug>[0-9]+)/$', views.detail, name='detail'),
]

我看不出你的观点,但应该是这样的:

from django.shortcuts import render, get_object_or_404
from .models import Article

def article(request, slug):
    article = get_object_or_404(Article, slug=slug)
    context = {
        'article': article
    }

    return render(request, 'article.html', context)

相关问题 更多 >