【问题标题】:How to write regex properly in re_path django 3如何在 re_path django 3 中正确编写正则表达式
【发布时间】:2020-10-31 03:57:15
【问题描述】:

我的代码的问题是,当我尝试单击帖子页面上的超链接时,我不断收到“找不到页面 (404) 错误,路径 'post/...' 不匹配”。我发了3个帖子。可能是正则表达式吗?因为我目前不擅长正则表达式。 如何将 views.py 与 urlpatterns 中的正确路径匹配?

我的 urls.py 是:

from django.contrib import admin
from django.urls import path, re_path

from blog import views as blog_views

urlpatterns = [
    path('post/', blog_views.post),
    
    re_path(r'^post(.*)/$', blog_views.post),

    path('about/'. blog_views.about),

    path('', blog_views.index),

    path('admin/', admin.site.urls)
]

我的views.py是:

from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse

from .models import Post

def index(request):
    posts = Post.objects.all()
    return render(request,'index.html', {'posts': posts})

def post(request, slug):
    print(slug)
    return render ('post.html',{'post': get_object_or_404(Post, slug=slug)})

def about(request):
    return render(request, 'about.html', {})

【问题讨论】:

    标签: python-3.x django regex web pycharm


    【解决方案1】:

    你可以使用类似的东西:

    re_path(r'post/(?P<slug>[\w-]+)/$', blog_views.posts),
    

    你真的需要在这里使用re_path吗?使用path会更简单:

    path('post/<slug:slug>/', blog_views.post),
    

    【讨论】:

    • 在我用于学习 django 的示例中,讲师在路径中使用了正则表达式,但那是 django 1.7 而我使用的是 Django 3,所以出现了混淆
    • 我也试过你的代码,但我现在得到一个 TypeError-> join() 参数必须是 str、bytes 或 os.PathLike 对象,而不是 'dict'
    • Django 1.7 真的很老了——最好找一本不同的书/教程来学习 Django,否则你可能会花很多时间更新代码以在新版本的 Django 上运行。跨度>
    • 除非我看到您的代码和完整的回溯,否则我无法确定导致 TypeError 的原因。直到刚才,我的回答还缺少逗号和斜杠,但我认为这不会导致问题。
    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多