django.core.exceptions.ImproperlyConfigured - django

`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

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

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

Value Error: Field 'id' expected a number but got 'favicon.ico

I am getting this error every time I execute an action on my application. Although it is not a fatal error I am sure it does effect the working of my program. Below is the traceback of the error. Can somebody that understands this please help.
[04/Jan/2021 07:13:14] "GET / HTTP/1.1" 200 6081
[04/Jan/2021 07:13:14] "GET /static/styles.css HTTP/1.1" 304 0
Internal Server Error: /favicon.ico/
Traceback (most recent call last):
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\fields_init_.py", line
1774, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'favicon.ico'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\core\handlers\exception.py", line 4
7, in inner
response = get_response(request)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\core\handlers\base.py", line 179, i
n _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\base.py", line 70, in
view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\base.py", line 98, in
dispatch
return handler(request, *args, **kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\detail.py", line 106,
in get
self.object = self.get_object()
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\views\generic\detail.py", line 36,
in get_object
queryset = queryset.filter(pk=pk)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\query.py", line 942, in f
ilter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\query.py", line 962, in _
filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\query.py", line 969, in _
filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\sql\query.py", line 1358,
in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\sql\query.py", line 1377,
in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\sql\query.py", line 1319,
in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\sql\query.py", line 1165,
in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\lookups.py", line 24, in
__init__
self.rhs = self.get_prep_lookup()
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\lookups.py", line 76, in
get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\Users\94ber\PycharmProjects\pythonProject\dev\venv\lib\site-packages\django\db\models\fields\__init__.py", line
1776, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got 'favicon.ico'.
[04/Jan/2021 07:13:15] "GET /favicon.ico/ HTTP/1.1" 500 138569
urls.py
from django.contrib import admin
from django.conf.urls import url, include
from.import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.conf import settings
from django.urls import path
from django.contrib.auth import views as auth_views
from accounts.views import (
registration_view,
account_view,
login_view,
)
from .views import *
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('accounts.urls')),
url(r'accounting/', include('accounting.urls')),
url(r'cashflow/', include('cashflow.urls')),
url(r'company/', include('company.urls')),
url(r'^$', views.homepage, name="home"),
url(r'about/$', views.about),
path('register/', registration_view, name="register"),
path('account/', account_view, name="account"),
path(r'^login/$',login_view, name="login"),
path('password_change/done/',
auth_views.PasswordChangeDoneView.as_view(template_name='registration/password_change_done.html'),
name='password_change_done'),
path('password_change/', auth_views.PasswordChangeView.as_view(template_name='registration/password_change.html'),
name='password_change'),
path('password_reset/done/',
auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_done.html'),
name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),
path('reset/done/',
auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'),
name='password_reset_complete'),
path('ex2', Ex2View.as_view(), name='ex2'),
path('<pk>/', Ledger_accountView.as_view(), name='ledger_account-detail'),
path('add', AddGeneralLedgerView.as_view(), name='add'),
path('<pk>/edit', Ledger_accountEditView.as_view(), name='ledger_account-edit'),]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Check your django template file. It might be missing the static tag for favicon.
<link rel="icon" href="{% static 'images/favicons/favicon.ico' %}">

Django " AttributeError: 'function' object has no attribute 'as_view' "

I am trying to make an index page with class based views that will have menu bar and with that menu bar it will redirect to new pages and takes forms as post requests. But whatever i do i always get the same error.
Here is the error ;
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check
databases=databases,
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\berat.berkol\anaconda3\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\berat.berkol\SystemConsole\SystemConsole\urls.py", line 25, in <module>
path('', UserUpdateView.as_view(), name='home'),
AttributeError: 'function' object has no attribute 'as_view'
And my project's urls.py ;
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from userupdate.views import UserUpdateView
app_name='userupdate'
urlpatterns = [
path('admin/', admin.site.urls),
path('login/',include('django.contrib.auth.urls')),
path('', UserUpdateView.as_view(), name='home'),
]
and my views.py ;
from django.shortcuts import render
from datetime import timedelta
from django.utils import timezone
from django.views.generic import TemplateView
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
from django.urls import reverse
import requests
from userupdate.forms import UserPassForm
from userupdate.forms import LoginForm
from django.views.generic import View
from django.contrib.auth.views import LoginView
from django.contrib.auth.mixins import LoginRequiredMixin
#csrf_protect
class UserUpdateView(LoginRequiredMixin,View):
emplate_name='home.html'
def get(self, request, *args, **kwargs):
return render(request,'home.html')
##method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(UserUpdateView, self).dispatch(self, request, *args, **kwargs)
#csrf_protect
class LoginUser(LoginView):
template_name = 'home.html' # your template
from_class = LoginForm() # your form
def get_success_url(self):
'''Here the part where you can implement your login logic'''
now = timezone.now()
# Get current day date object
# like: 12/02/2019 00:00:00
today = now.replace(minute=0).replace(second=0).replace(microsecond=0)
# Get the client from the user object
client = self.request.user.cli
# Get all the user today's logins and count them
client_logins = models.ClientLogins.objects.filter(
client=client,
date__gte=today,
date__lte=today + timedelta(days=1)
).count()
if client_logins < 1: # Or: if not client_logins:
# create a login tracker record
models.ClientLogins.objects.create(
client=client,
date=now # Store the date where the user logged in the website
)
return reverse_lazy('home')
# Or redirect to: settings.LOGIN_REDIRECT_URL
request.session.get_expire_at_browser_close()
return super().get_success_url()
#csrf_protect
class passResetView(View):
def get(self,request):
form=UserUpdateForm()
return render('basarili')
def post(self,request):
passResetuser=self.model.objects.get(pk=2)
form=UserUpdateForm(request.POST,instance=passResetuser)
if form.is_valid():
username=form.cleaned_data('username')
password=form.cleaned_data('password')
number=form.cleaned_data('number')
message=form.cleaned_data('message')
context={'form':form}
return render(request,'home.html',context)
I don't know if it's required but here is my app's urls.py ;
from django.urls import path, re_path
from django.contrib.auth.views import LoginView
from userupdate.views import HomeView
from django.contrib.auth import views as auth_views
app_name='userupdate'
urlpatterns = [
path('', views.UserUpdateView.as_view(template_name='home.html'), name='home'),
path('login/',
LoginView.as_view(
template_name='login.html'),
name="login"),
#path('passResetView',views.passResetView.as_view(template_name="home.html"),name='passResetView'),
path('passreset/',
passResetView.as_view(
template_name='passreset.html'),
name="PasswordReset"),
]
I haven't configured the form pages yet so ignore them for now.
I will build them with the FormView.
By the way I tried the TemplateView also but i didn't help its makes the same error.
You can't use #csrf_protect on a class-based view, or at least not directly. This decorator will return a function, and that function of course has no .as_view() method.
You can work with the #method_decorator [Django-doc], which will decorate the class:
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
#method_decorator(csrf_exempt, name='dispatch')
class UserUpdateView(LoginRequiredMixin,View):
template_name = 'home.html'
# …
That being said, it is often not a good idea to make a CSRF exempt, since that makes your view vulnerable to Cross-Site Request Forgery [wiki].

Django 1.11 circular import error, Also url pattern... current path doesn't match

I'm using django 1.11. This is my traceback:
Traceback (most recent call last):
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\utils\autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\core\management\commands\runserver.py", line 124, in
inner_run
self.check(display_num_errors=True)
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\core\management\base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\core\management\base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\core\checks\urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\core\checks\urls.py", line 26, in check_resolver
return check_method()
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\urls\resolvers.py", line 255, in check
warnings.extend(check_resolver(pattern))
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\core\checks\urls.py", line 26, in check_resolver
return check_method()
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\urls\resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Python3\envs\myDjangoEnv\lib\site-
packages\django\urls\resolvers.py", line 414, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module
'irbSite.urls' from 'C:\\Users\\doxpr\\Desktop\\WorkingProje
ctClassBased Views\\WorkingProjectClassBased
Views\\capstoneProject\\capstoneProject\\irbSite\\urls.py'>' does not appear
to have any p
atterns in it. If you see valid patterns in the file then the issue is
probably caused by a circular import.
As seen above, I'm getting a circular import error when I include:
url(r'irbSite/', include('irbSite.urls', namespace = 'irbSite')),
url(r'irbSite/', include('django.contrib.auth.urls'))
in urls.py in the project folder:
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', auth_views.LoginView.as_view(template_name =
'irbSite/login.html'),name='login'),
url(r'irbSite/', include('irbSite.urls', namespace = 'irbSite')),
url(r'irbSite/', include('django.contrib.auth.urls'))
]
However, if I do not include it my login page will appear, but when I click the register link I get this error:
"url patterns" ... "^admin/ ^$ [name='login'] The current path, register.html, didn't match any of these."
My directory (not code):
irbsite
pycache
migrations
static
templates
init.py
admin.py
apps.py
forms.py
models.py
tests.py
urls.py
views.py
project
pycache
init.py
settings.py
urls.py
wsgi.py
manage.py
My views.py (in irbSite folder):
from django.contrib.auth import login, logout
from django.core.urlresolvers import reverse_lazy
from django.views.generic import CreateView
from . import forms
class Registration(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'register.html'
My urls.py (in irbSite folder):
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'irbSite'
ulrpatterns = [
url(r'logout/$', auth_views.LogoutView.as_view(),name='logout'),
url(r'register/$',views.Registration.as_view(template_name =
'irbSite/register.html'),name='registration'),
]
I'm modifying a tutorial that I followed from a udemy course. I've hit a wall, any advice?
Note that you’re not getting a circular import error, the message just suggests that it might be a circular import causing the problem.
In this case, you have a typo in your irbSite/urls.py. It should be urlpatterns not ulrpatterns.

"No data received" with custom handler403 in django

When setting a simple handler403 for Django:
from django.conf.urls import url
from django.core.exceptions import PermissionDenied
from django.views.generic import TemplateView
class PermissionDeniedView(TemplateView):
template_name = '403.html'
handler403 = PermissionDeniedView.as_view()
def my_view(request):
raise PermissionDenied
urlpatterns = [
url(r'^$', my_view),
]
The browser does not receive any data (ERR_EMPTY_RESPONSE in chrome), and some errors appear on the log:
Traceback (most recent call last):
File "/usr/lib64/python2.7/wsgiref/handlers.py", line 86, in run
self.finish_response()
File "/usr/lib64/python2.7/wsgiref/handlers.py", line 127, in finish_response
for data in self.result:
File "/home/foo/.virtualenvs/bar/lib/python2.7/site-packages/django/template/response.py", line 171, in __iter__
raise ContentNotRenderedError('The response content must be '
ContentNotRenderedError: The response content must be rendered before it can be iterated over.
[20/May/2015 07:26:25]"GET / HTTP/1.1" 500 59
Traceback (most recent call last):
File "/usr/lib64/python2.7/SocketServer.py", line 599, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib64/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/home/foo/.virtualenvs/bar/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 102, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/usr/lib64/python2.7/SocketServer.py", line 655, in __init__
self.handle()
File "/home/foo/.virtualenvs/bar/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 182, in handle
handler.run(self.server.get_app())
File "/usr/lib64/python2.7/wsgiref/handlers.py", line 92, in run
self.close()
File "/usr/lib64/python2.7/wsgiref/simple_server.py", line 33, in close
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
TemplateView returns a TemplateResponse instance with lazy content rendering by default, and is not suitable as is for handler403.
To force this view to render it's content, make sure .render() is called before returning the response:
class PermissionDeniedView(TemplateView):
template_name = '403.html'
def dispatch(self, request, *args, **kwargs):
response = super(PermissionDeniedView, self).dispatch(request, *args, **kwargs)
response.render()
return response

django test client fails, but url works

I'm having a strange problem with some unit tests, which are quite simple, but are failing. The strange thing is that this work with runserver, i.e, I can render the perfil_usuario view, but in unit tests this is failing with NoReverseMatch.
First of all, this my main urlconf:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r"^$", include("traxx.hotsite.urls", namespace="hotsite")),
url(r'^admin/', include(admin.site.urls)),
url(r'^imperavi/', include('imperavi.urls')),
url(r"^app/", include("traxx.sistema.urls", namespace="app")),
url(r"^usuarios/", include("traxx.usuarios.urls", namespace="usuarios")),
url(r"^notificacoes/", include("traxx.notificacoes.urls", namespace="notificacoes")),
url(r"^clientes/", include("traxx.clientes.urls", namespace="clientes")),
)
My usuarios (4th url conf in main) urlconf is the following:
# coding: utf-8
from django.conf.urls import patterns, include, url
urlpatterns = patterns("traxx.usuarios.views",
url(r"^perfil/(?P<id>\d+)/$", "perfil_usuario", name="perfil"),
url(r"^configuracoes/(?P<id>\d+)/$", "configuracoes_usuario", name="configuracoes"),
url(r"^login/$", "login", name="login"),
url(r"^logout/$", "logout", name="logout"),
)
This is the view:
def perfil_usuario(request, id):
usuario = get_object_or_404(Usuario, pk=id)
return render(request, "usuarios/perfil_usuario.html", {"usuario": usuario})
And this is the failing unit test:
class PerfilUsuarioViewTestCase(TransactionTestCase):
"""Testes para a view home"""
def setUp(self):
pass
def test_get_perfil_usuario(self):
usuario_fake = mommy.make(Usuario, nome_usuario="teste")
c = Client()
resposta = c.get(reverse("usuarios:perfil", kwargs={"id": usuario_fake.pk}))
self.assertEqual(200, resposta.status_code)
The reverse call reverse("usuarios:perfil", kwargs={"id": usuario_fake.pk}) works just fine, outputing /usuarios/perfil/1/.
Call to reverse
>>> from django.core.urlresolvers import reverse
>>> reverse("usuarios:perfil", kwargs={"id":1})
/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/imperavi/views.py:1: DeprecationWarning: the md5 module is deprecated; use hashlib instead
import md5
'/usuarios/perfil/1/'
I'm using Django 1.6.
Full traceback
Traceback (most recent call last):
File "/home/george/projetos/traxx/src/traxx/testes/usuarios/views.py", line 21, in test_get_perfil_usuario
resposta = c.get(reverse("usuarios:perfil", kwargs={"id": usuario_fake.pk}))
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/client.py", line 473, in get
response = super(Client, self).get(path, data=data, **extra)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/client.py", line 280, in get
return self.request(**r)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/client.py", line 444, in request
six.reraise(*exc_info)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/george/projetos/traxx/src/traxx/usuarios/views.py", line 12, in perfil_usuario
return render(request, "usuarios/perfil_usuario.html", {"usuario": usuario})
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/shortcuts/__init__.py", line 53, in render
return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/loader.py", line 169, in render_to_string
return t.render(context_instance)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/base.py", line 140, in render
return self._render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/utils.py", line 85, in instrumented_test_render
return self.nodelist.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/base.py", line 840, in render
bit = self.render_node(node, context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/debug.py", line 78, in render_node
return node.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 123, in render
return compiled_parent._render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/utils.py", line 85, in instrumented_test_render
return self.nodelist.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/base.py", line 840, in render
bit = self.render_node(node, context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/debug.py", line 78, in render_node
return node.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 155, in render
return self.render_template(self.template, context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/loader_tags.py", line 137, in render_template
output = template.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/base.py", line 140, in render
return self._render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/test/utils.py", line 85, in instrumented_test_render
return self.nodelist.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/base.py", line 840, in render
bit = self.render_node(node, context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/debug.py", line 78, in render_node
return node.render(context)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/defaulttags.py", line 447, in render
six.reraise(*exc_info)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/template/defaulttags.py", line 433, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app)
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 509, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/home/george/projetos/.virtualenvs/traxx/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 429, in _reverse_with_prefix
(lookup_view_s, args, kwargs, len(patterns), patterns))
NoReverseMatch: Reverse for 'perfil' with arguments '(None,)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'usuarios/perfil/(?P<id>\\d+)/$']
As you can see from the traceback, id passed in kwargs is evaluated to None. This is why it is not matching the usuarios/perfil/(?P<id>\\d+)/$ url pattern.
In other words usuario_fake.pk value is None.
UPD:
the problem was actually in the template which the traceback was complaining about.