Home > Enterprise >  django.core.exceptions.ImproperlyConfigured
django.core.exceptions.ImproperlyConfigured

Time:01-04

`I have watched a tutorial. But that was an old version of Django 1.1 and now I am using Django 4.1.So there is a problem that is telling me about django.core.exceptions.ImproperlyConfigured: "post/(?\d )$" is not a valid regular expression: unknown extension ?<p at position 6. I didn't get it what it was

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 file

"""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': '/'}),
]

blog.urls file here


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'),

]

Here is the error message

C:\Users\Tahmid Arafat Nabil\My_Django_Stuff\blog_project\mysite>python manage.py migrate
Traceback (most recent call last):
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 235, in _compile
    return re.compile(regex)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\re.py", line 252, in compile
    return _compile(pattern, flags)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\re.py", line 304, in _compile
    p = sre_compile.compile(pattern, flags)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\sre_compile.py", line 764, in compile
    p = sre_parse.parse(p, flags)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\sre_parse.py", line 950, in parse
    p = _parse_sub(source, state, flags & SRE_FLAG_VERBOSE, 0)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\sre_parse.py", line 443, in _parse_sub
    itemsappend(_parse(source, state, verbose, nested   1,
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\sre_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:\Users\Tahmid Arafat Nabil\My_Django_Stuff\blog_project\mysite\manage.py", line 22, in <module>
    main()
  File "C:\Users\Tahmid Arafat Nabil\My_Django_Stuff\blog_project\mysite\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\base.py", line 448, in execute
    output = self.handle(*args, **options)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\base.py", line 96, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\commands\migrate.py", line 97, in handle
    self.check(databases=[database])
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\management\base.py", line 475, in check
    all_issues = checks.run_checks(
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
    return check_method()
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 477, in check
    messages.extend(check_resolver(pattern))
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
    return check_method()
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 477, in check
    messages.extend(check_resolver(pattern))
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
    return check_method()
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 387, in check
    warnings.extend(self.pattern.check())
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 213, in check
    warnings.extend(self._check_pattern_startswith_slash())
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 164, in _check_pattern_startswith_slash
    regex_pattern = self.regex.pattern
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.py", line 142, in __get__
    instance.__dict__["regex"] = instance._compile(pattern)
  File "C:\Users\Tahmid Arafat Nabil\anaconda3\lib\site-packages\django\urls\resolvers.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

CodePudding user response:

I guess your regex is not valid.
Change it to
re_path(r'post/(?P<pk>\d )/$',views.PostDetailView.as_view(),name='post_detail')

CodePudding user response:

You should format your path according to correct regex path.

For example:

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'),

A better way of doing this would be to use path itself, like so:

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'),
  • Related