Python 3.x 如何在re_path django 3中正确写入正则表达式
我的代码的问题是,当我尝试单击我的帖子页面上的超链接时,我不断收到“页面未找到(404)错误,路径“post/…”不匹配”。我发了3篇帖子。可能是正则表达式吗?因为我现在不擅长正则表达式。 如何将views.py与urlpatterns中的正确路径匹配 我的URL.py是:Python 3.x 如何在re_path django 3中正确写入正则表达式,python-3.x,django,regex,web,pycharm,Python 3.x,Django,Regex,Web,Pycharm,我的代码的问题是,当我尝试单击我的帖子页面上的超链接时,我不断收到“页面未找到(404)错误,路径“post/…”不匹配”。我发了3篇帖子。可能是正则表达式吗?因为我现在不擅长正则表达式。 如何将views.py与urlpatterns中的正确路径匹配 我的URL.py是: from django.contrib import admin from django.urls import path, re_path from blog import views as blog_views ur
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)
]
My 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', {})
您可以使用以下内容:
re_path(r'post/(?P<slug>[\w-]+)/$', blog_views.posts),
在我学习django时使用的示例中,讲师在路径中使用了regex,但那是django 1.7,我使用的是django 3,所以有一个混合,我也尝试过你的代码,但现在得到一个TypeError->join()参数必须是str、bytes或os.PathLike对象,并非“dict”Django 1.7真的很旧-最好找一本不同的书/教程来学习Django,否则您可能会花费大量时间更新代码以使用新版本的Django运行。除非看到您的代码和完整的回溯,否则我无法判断是什么导致了类型错误。刚才我的答案是缺少逗号和斜杠,但我认为这不会造成问题。
path('post/<slug:slug>/', blog_views.post),