django.core.exceptions.ImproperlyConfigured



我看过一个教程。但那是Django 1.1的旧版本,现在我用的是Django 4.1。所以有一个问题告诉我django.core.exceptions.ImproperlyConfigured: "post/(?d+)$"不是一个有效的正则表达式:未知扩展?<p在位置6。我不知道它是什么>

views.py

from django.shortcuts import render,get_object_or_404,redirect
from django.utils import timezone
from blog.models import Post,Comment
from blog.forms import PostForm,CommentForm
from django.urls import reverse_lazy
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import (TemplateView,ListView,DetailView,DeleteView,CreateView,UpdateView)

# Create your views here.
class AboutView(TemplateView):
template_name = 'about.html'
class PostListView(ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
class PostDetailView(DetailView):
model = Post

class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post

class PostUpdateView(LoginRequiredMixin,UpdateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post

class DraftListView(LoginRequiredMixin,ListView):
login_url = '/login/'
redirect_field_name = 'blog/post_list.html'
model = Post
def get_queryset(self):
return Post.objects.filter(published_date__isnull=True).order_by('created_date')

class PostDeleteView(LoginRequiredMixin,DeleteView):
model = Post
success_url = reverse_lazy('post_list')
#######################################
## Functions that require a pk match ##
#######################################
@login_required
def post_publish(request, pk):
post = get_object_or_404(Post, pk=pk)
post.publish()
return redirect('post_detail', pk=pk)
@login_required
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/comment_form.html', {'form': form})

@login_required
def comment_approve(request, pk):
comment = get_object_or_404(Comment, pk=pk)
comment.approve()
return redirect('post_detail', pk=comment.post.pk)

@login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
post_pk = comment.post.pk
comment.delete()
return redirect('post_detail', pk=post_pk)

urls . py文件
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import:  from my_app import views
2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
1. Add an import:  from other_app.views import Home
2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path, include
from django.contrib import admin
from django.contrib.auth import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
path('accounts/login/', views.LoginView.as_view(), name='login'),
path('accounts/logout/', views.LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}),
]

博客。url文件


from django.urls import path,re_path
from blog import views
urlpatterns = [
path('',views.PostListView.as_view(),name='post_list'),
path('about/',views.AboutView.as_view,name='about'),
re_path(r'post/(?<pk>d+)$',views.PostDetailView.as_view(),name='post_detail'),
path('post/new/',views.CreatePostView.as_view(),name='post_new'),
re_path(r'post/(?<pk>d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'),
re_path(r'post/(?<pk>d+)/remove/$',views.PostDeleteView.as_view(),name='post_remove'),
path('drafts/',views.DraftListView.as_view(),name='post_draft_list'),
re_path(r'post/(?<pk>d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'),
re_path(r'comment/(?<pk>d+)/approve/$',views.comment_approve,name='comment_approve'),
re_path(r'comment/(?<pk>d+)/remove/$',views.comment_remove,name='comment_remove'),
re_path(r'post/(?<pk>d+)/publish/$',views.post_publish,name='post_publish'),
]

下面是错误信息

C:UsersTahmid Arafat NabilMy_Django_Stuffblog_projectmysite>python manage.py migrate
Traceback (most recent call last):
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangourlsresolvers.py", line 235, in _compile
return re.compile(regex)
File "C:UsersTahmid Arafat Nabilanaconda3libre.py", line 252, in compile
return _compile(pattern, flags)
File "C:UsersTahmid Arafat Nabilanaconda3libre.py", line 304, in _compile
p = sre_compile.compile(pattern, flags)
File "C:UsersTahmid Arafat Nabilanaconda3libsre_compile.py", line 764, in compile
p = sre_parse.parse(p, flags)
File "C:UsersTahmid Arafat Nabilanaconda3libsre_parse.py", line 950, in parse
p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
File "C:UsersTahmid Arafat Nabilanaconda3libsre_parse.py", line 443, in _parse_sub
itemsappend(_parse(source, state, verbose, nested + 1,
File "C:UsersTahmid Arafat Nabilanaconda3libsre_parse.py", line 748, in _parse
raise source.error("unknown extension ?<" + char,
re.error: unknown extension ?<p at position 6
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:UsersTahmid Arafat NabilMy_Django_Stuffblog_projectmysitemanage.py", line 22, in <module>
main()
File "C:UsersTahmid Arafat NabilMy_Django_Stuffblog_projectmysitemanage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocoremanagement__init__.py", line 446, in execute_from_command_line
utility.execute()
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocoremanagement__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocoremanagementbase.py", line 402, in run_from_argv
self.execute(*args, **cmd_options)
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocoremanagementbase.py", line 448, in execute
output = self.handle(*args, **options)
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocoremanagementbase.py", line 96, in wrapped
res = handle_func(*args, **kwargs)
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocoremanagementcommandsmigrate.py", line 97, in handle
self.check(databases=[database])
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocoremanagementbase.py", line 475, in check
all_issues = checks.run_checks(
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocorechecksregistry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocorechecksurls.py", line 14, in check_url_config
return check_resolver(resolver)
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocorechecksurls.py", line 24, in check_resolver
return check_method()
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangourlsresolvers.py", line 477, in check
messages.extend(check_resolver(pattern))
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocorechecksurls.py", line 24, in check_resolver
return check_method()
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangourlsresolvers.py", line 477, in check
messages.extend(check_resolver(pattern))
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangocorechecksurls.py", line 24, in check_resolver
return check_method()
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangourlsresolvers.py", line 387, in check
warnings.extend(self.pattern.check())
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangourlsresolvers.py", line 213, in check
warnings.extend(self._check_pattern_startswith_slash())
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangourlsresolvers.py", line 164, in _check_pattern_startswith_slash
regex_pattern = self.regex.pattern
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangourlsresolvers.py", line 142, in __get__
instance.__dict__["regex"] = instance._compile(pattern)
File "C:UsersTahmid Arafat Nabilanaconda3libsite-packagesdjangourlsresolvers.py", line 237, in _compile
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: "post/(?<pk>d+)$" is not a valid regular expression: unknown extension ?<p at position 6

我猜你的正则表达式是无效的。
改为
re_path(r'post/(?P<pk>d+)/$',views.PostDetailView.as_view(),name='post_detail')

您应该根据正确的正则表达式路径来格式化您的路径。

例如:

re_path(r'post/(?P<pk>d+)$',views.PostDetailView.as_view(),name='post_detail'),
re_path(r'post/(?P<pk>d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'),
re_path(r'post/(?P<pk>d+)/remove/$',views.PostDeleteView.as_view(),name='post_remove'),
re_path(r'post/(?P<pk>d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'),
re_path(r'comment/(?P<pk>d+)/approve/$',views.comment_approve,name='comment_approve'),
re_path(r'comment/(?P<pk>d+)/remove/$',views.comment_remove,name='comment_remove'),
re_path(r'post/(?P<pk>d+)/publish/$',views.post_publish,name='post_publish'),

更好的方法是使用path本身,如下所示:

path('post/<int:pk>',views.PostDetailView.as_view(),name='post_detail'),
path('post/<int:pk>/edit/',views.PostUpdateView.as_view(),name='post_edit'),
path('post/<int:pk>/remove/',views.PostDeleteView.as_view(),name='post_remove'),
path('post/<int:pk>/comment/',views.add_comment_to_post,name='add_comment_to_post'),
path('comment/<int:pk>/approve/',views.comment_approve,name='comment_approve'),
path('comment/<int:pk>/remove/',views.comment_remove,name='comment_remove'),
path('post/<int:pk>/publish/',views.post_publish,name='post_publish'),

相关内容

  • 没有找到相关文章

最新更新