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

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' %}">

Related

django.core.exceptions.ImproperlyConfigured

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

Modifying oscarapi to show some endpoints as public from admin endpoints

What I am trying to achieve is to customize the oscarapi to expose the partner api to be public api instead of just for admin
I have followed the docs on how to customize the api and also did as suggested by Jamie Marshall in
Extending django-oscarapi API ROOT to custom API class
So far I am able to overwrite the root.py file but failing to get oscar see the new urls.py file.
My work so far is as follows
I created a api_customization/views/partner.py file
I created a api_customization/views/root.py file
I tried to extend the urls.py file by creating a api_customization/urls.py file
However, I'm getting the following error
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.7/contextlib.py", line 74, in inner return func(*args, **kwds)
File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc)
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc
File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs)
File "/code/.../forked_apps/api_customization/views/root.py", line 52, in api_root apis = PUBLIC_APIS(request, format)
File "/code/.../forked_apps/api_customization/views/root.py", line 29, in PUBLIC_APIS ("partners", reverse("partner-list", request=r, format=f)),
File "/usr/local/lib/python3.7/site-packages/rest_framework/reverse.py", line 47, in reverse url = _reverse(viewname, args, kwargs, request, format, **extra)
File "/usr/local/lib/python3.7/site-packages/rest_framework/reverse.py", line 60, in _reverse url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
File "/usr/local/lib/python3.7/site-packages/django/urls/base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 685, in _reverse_with_prefix raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'partner-list' not found. 'partner-list' is not a valid view function or pattern name.
[09/Jul/2021 21:18:13] "GET /api/ HTTP/1.1" 500 136185
views/partner.py
from oscarapi.utils.loading import get_api_class
from oscar.core.loading import get_model
from rest_framework import generics
PartnerSerializer = get_api_class("serializers.product", "PartnerSerializer")
Partner = get_model("partner", "Partner")
class PublicPartnerList(generics.ListCreateAPIView):
queryset = Partner.objects.all()
serializer_class = PartnerSerializer
urls.py
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from oscarapi.utils.loading import get_api_class
from oscarapi import urls
PublicPartnerList = get_api_class("views.partner", "PublicPartnerList")
urls.urlpatterns += [
path("partners1/", PublicPartnerList.as_view(), name="partner-list"),
]
urls.urlpatterns += format_suffix_patterns(urls.urlpatterns)
views/root.py
import collections
from django.conf import settings
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
__all__ = ("api_root",)
def PUBLIC_APIS(r, f):
return [
# other urls .......
("partners", reverse("partner-list", request=r, format=f)),
]
# remaining file content ......
I need a direction or a hint on how to achieve this
Any help is appreciated
I found a solution to this and might be helpful form someone
I had to do the same steps done for root.py file to get my app recognise the custom urls.py file
So what I did
copy the content of urls.py
modify the file to suit my needs
update my app urls.py file to point to the custom urls.py file of the api
//So from this
path("api/", include("oscarapi.urls")),
//To this
path("api/", include("APP_NAME.forked_apps.api_customization.urls")),

Problem in Django 2.2 with Debug=True on Ubuntu

I am trying to run a project in Django 2.2 with Debug=True on Ubuntu but I get this error in python manager.py runserver:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 581, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 588, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf 'moeaforhdl.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
This is /myparentapp/urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'', include('moeaforhdlweb.urls')),
url(r'^admin/', admin.site.urls),
url(r'^tinymce/', include('tinymce.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is /mychildapp/urls.py:
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^help/$', views.help, name='help')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I test this project on Windows 10 and it works perfectly, but not on Ubuntu.
Besides, if I comment this line:
url(r'', include('moeaforhdlweb.urls'))
it works.
Any help will be grateful, thanks a lot.

TyperError Django while using urls.py

I'm beginner and I'm using Django 1.8.3 and Python 2.7.3.
I'm trying to run server and get the following error:
Traceback:
File "/home/mercurial/internet.django/djangoenv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
108. response = middleware_method(request)
File "/home/mercurial/internet.django/djangoenv/local/lib/python2.7/site-packages/django/middleware/common.py" in process_request
74. if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
File "/home/mercurial/internet.django/djangoenv/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in is_valid_path
647. resolve(path, urlconf)
File "/home/mercurial/internet.django/djangoenv/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
522. return get_resolver(urlconf).resolve(path)
File "/home/mercurial/internet.django/djangoenv/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
366. for pattern in self.url_patterns:
File "/home/mercurial/internet.django/djangoenv/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns
402. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/mercurial/internet.django/djangoenv/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
396. self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py" in import_module
37. __import__(name)
File "/home/mercurial/internet.django/bzi/bzi/urls.py" in <module>
24. url(r'^domains/', include('mailserver.urls')),
File "/home/stas/mercurial/internet.django/djangoenv/local/lib/python2.7/site-packages/django/conf/urls/__init__.py" in include
33. urlconf_module = import_module(urlconf_module)
File "/usr/lib/python2.7/importlib/__init__.py" in import_module
37. __import__(name)
File "/home/mercurial/internet.django/bzi/mailserver/urls.py" in <module>
5. url(r'^$', views.domains, name='domains'),
Exception Type: TypeError at /domains
Exception Value: 'function' object has no attribute '__getitem__'
My project file urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^domains/', include('mailserver.urls')),
]
My app mailserver file urls.py:
from django.conf.urls import patterns, url, include
from . import views
urlpatterns = patterns[
url(r'^$', views.domains),
]
What am I doing wrong?
You shouldn't have the patterns name:
urlpatterns = [
url(r'^$', views.domains),
]
The error is in urls.py, you should write:
urlpatterns = [
url(r'^$', views.domains),
]
Right now you are using square brackets "[]" after patterns - that is signal for python interpreter to call patterns.__getitem__() method, which is absent. That's why you get an error.

"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