美文网首页
Django2.1中基于正则表达式的路由机制

Django2.1中基于正则表达式的路由机制

作者: 山坡上的斐德洛 | 来源:发表于2018-12-23 16:44 被阅读0次

首先看前端, 这里只列出了重点,就是其中的a标签

    {% for post in posts %}
        <p style="font-family: '微软雅黑 Light'; font-size: 16pt; font-weight: bold;">
            <a href="/post/{{ post.slug }}">{{ post.title }}</a>
        </p>

再看urls.py中


捕获.PNG

要使用正则表达式的路由,要新引入一个量:re_path

再看views.py
获取数据库数据,返回到前端

def showpost(req, slug):
    template = get_template("post.html")
    try:
        post = models.Post.objects.get(slug=slug)
        if post != None:
            html = template.render(locals())
            return HttpResponse(html)
    except:
        return redirect('/')    # 返回首页

相关文章

网友评论

      本文标题:Django2.1中基于正则表达式的路由机制

      本文链接:https://www.haomeiwen.com/subject/spunkqtx.html