Invalid syntax when trying to create custom http errors - django

I'm trying to make custom http error pages. And as usual the django docs are really hard to understand.
I'm trying my best to follow this doc: https://docs.djangoproject.com/en/2.1/topics/http/views/#customizing-error-views
So I have set DEBUG = False
I have set ALLOWED_HOSTS = ['*']
In my views.py (not inside an app)
def server_error(request, exception):
return render(request, 'mysite/errors/500.html')
And in my urls.py (not inside an app), after all paths.
urlpatterns = [
path('', views.index, name='index'),
.......etc
handler500 = 'mysite.views.server_error'
]
When I run my server, I get instant error on handler500 in urls.py.
handler500 = 'mysite.views.server_error'
^
SyntaxError: invalid syntax
I also made a simple '500.html' under 'templates/errors'.
I have tried with importing handler, even though I read that I should not.
I tried with removing 'mysite' in location for view etc.
I can't seem to find anything about this SyntaxError on my handler?

Put handler500 = 'mysite.views.server_error' outside of urlpatterns at file level.
urlpatterns = [
path('', views.index, name='index'),
.......
]
handler500 = 'mysite.views.server_error'
Also add 500 response status in the error view
def server_error(request):
return render(request, 'mysite/errors/500.html', status=500)

Related

Redirect all page not found to home page

I would like to redirect all 404 pages to a home page. I try this but it don't work
app/views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
def home(request): return HttpResponse('<h1> HOME </h1>')
def redirectPNF(request, exception): return redirect('home')
app/urls.py
from . import views
urlpatterns = [ path('home', views.home, name="home"), ]
app/settings.py
handler404 = 'app.views.redirectPNF'
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
DEBUG = False
Just Add this line in urls.py instead of settings.py
Everything else seems ok.
It is also mentioned in the django documentation that setting handler variables from anywhere else will have no effect. It has to be set from URLconf
The default error views in Django should suffice for most web applications, but can easily be overridden if you need any custom behavior. Specify the handlers as seen below in your URLconf (setting them anywhere else will have no effect).
app/urls.py
from . import views
handler404 = 'app.views.redirectPNF' # Added this line in URLconf instead of settings.py
urlpatterns = [ path('home', views.home, name="home"), ]

Django root path not found after adding handler404

I added a handler404 to my project and it immediately broke the root path and the 404 page is shown.
I wonder how I need to change my urls.py to make it work correctly with i18n_patterns. I would appreciate any advice on the issue.
The URLs with the language prefix work fine.
mysite.com 404 why????
mysite.com/en/ OK
mysite.com/fr/ OK
mysite.com/gffg 404
Here's the urls.py of my project.
urlpatterns = i18n_patterns(
path('admin/', admin.site.urls),
path('i18n/', include('django.conf.urls.i18n')),
#apps
path('', include('apps.webapp.urls')),
path('user/', include('apps.userapp.urls')),
path('client-area/', include('apps.accountapp.urls')),
#additional paths
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
path('ckeditor/', include('ckeditor_uploader.urls')),
path('rosetta/', include('rosetta.urls')),
) + [
path("robots.txt", TemplateView.as_view(template_name="web/robots.txt", content_type="text/plain"),),
]
handler404 = 'apps.webapp.views.handler404'
i18n_patterns has a keyword argument prefix_default_language whose default is True. According to the documentation it:
Setting prefix_default_language to False removes the prefix
from the default language
(LANGUAGE_CODE).
This can be useful when adding translations to existing site so that
the current URLs won’t change.
You haven't set this to False in your code so you end up not having a pattern that would match mysite.com. Add the keyword argument to the function call so that you don't need the prefix for the default language:
urlpatterns = i18n_patterns(
path('admin/', admin.site.urls),
...,
prefix_default_language=False,
)
I created custom error view to handle this issue
from django.shortcuts import render, redirect
from django.conf import settings
def handler_error_view(request, *args, **kwargs):
for lang_code, _ in settings.LANGUAGES:
if request.path.startswith('/'+lang_code):
return render(request, 'generals/your_error_template.html')
return redirect('/'+settings.LANGUAGE_CODE+request.path)

Reverse for 'index' not found. 'index' is not a valid view function or pattern name

I have a simple return HttpResponseRedirect(reverse('index')) where 'index' is the name of the view. on running the server the index view is correctly displayed but gives out this error "NoReverseMatch at /vehicle_movement/checkinview"on redirecting.
I was working on django 1.1 for the same project but switched to django 2.2 later. Redirect was working fine with url django 1.1 but gives this error with path django 2.2. Another change that i have done is earlier in 1.1 project the index view url was written in the main url.py but now it is written in the apps urls.py.
This is views.py
def index(request):
return render(request,'vehicle_movement/index.html',{})
def CheckinView(request):
if request.method == "POST":
checkin_form = CheckinForm(data = request.POST)
if checkin_form.is_valid():
checkin_form.save()
return HttpResponseRedirect(reverse('index'))
else:
HttpResponse("Error")
else:
checkin_form = CheckinForm()
return render(request,'vehicle_movement/checkin.html',{'checkin_form':checkin_form})
This is the Main urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(('vehicle_movement.urls','vehicle_movement'),namespace = 'vehicle_movement')),
]
This is app urls.py
app_name = 'vehicle_movement'
urlpatterns = [
path('', views.index, name='index'),
path('index', views.index, name='index'),
]
This is the structure
Warehouse
-Warehouse
-init.py
-settings.py
-urls.py
-static
-templates
-vehicle_movement
-urls.py
-views.py
The TEMPLATES_DIR
TEMPLATES_DIR = os.path.join(BASE_DIR,'templates')
``
You've namespaced your app urls, so you need to use that namespace when reversing them:
reverse('vehicle_movement:index')
But you've also got two paths with the same name in your app urls, which will cause conflicts, if not an error. Delete one of them.
Check name="htmlfilename" in app urls is correct or not.

Page not found error happens-Can <str:id> be used?

Page not found error happens-Can be used?
I wrote in urls.py
from django.conf.urls import url
from app import views
urlpatterns = [
url('^data/<str:id>', views.data, name='data'),
]
in views.py
def data(id):
・
・
・
return None
For example, when I access http://127.0.0.1:8000/data/AD04958 ,
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/data/AD04958
error happens.
I think I can write this url http://127.0.0.1:8000/data/AD04958 into '^data/' in urls.py,so I really cannot understand why this error happens. id is not save in Database,does it cause this error?
What is wrong in my codes?How should I fix this?
For Django<=1.11.x
urlpatterns = [
url(r'^data/(?P<id>[\w.-]+)/$', views.data, name='data'),
]
For Django>=2
urlpatterns = [
path('^data/<str:id>', views.data, name='data'),
]

How do you pass 'exception' argument to 403 view?

**Edit: Of course, it dawns on me that this doesn't have anything to do with the UserPassesTextMixin, because this error pops up when trying to visit the 403 page directly. Still not sure what to make of it though.
I'm attempting to use UserPassesTestMixin to check which model's edit view is being requested and run a test specific to that model to see if the user should have access. Nothing is working yet, I'm just trying to get a feel for how this mixin operates. Upon returning false in the test_func, the view tries to redirect to /403/, but I get the below error.
TypeError at /403/
permission_denied() missing 1 required positional argument: 'exception'
view
class DeviceUpdate(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Device
template_name_suffix = '_update_form'
form_class = DeviceUpdateForm
def test_func(self):
return edit_permission_test(self.get_object())
...
perms.py
def edit_permission_test(model_object):
possible_models = ['Device',]
if isinstance(model_object, Device):
print('This is a Device model object')
return True
else:
print('This doesnt look like a Device model object')
return False
I cant seem to find anything out there on the interwebs that helps with this error.
I think this issue just had to do with how the url patterns were configured for local development. Previously my main urls.py looked like this:
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name="home"),
...
# Your stuff: custom urls includes go here
url(r'^devices/', include('auto_toner.urls', namespace='auto_toner', app_name='auto_toner'), name="devices"),
url(r'^400/$', default_views.bad_request),
url(r'^403/$', default_views.permission_denied),
url(r'^404/$', default_views.page_not_found),
url(r'^500/$', default_views.server_error),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I changed the URLs to include kwargs in the pattern if settings.DEBUG was True.
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}),
url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}),
url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}),
url(r'^500/$', default_views.server_error),
]
if 'debug_toolbar' in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]