How can I override standard handler404, handler403, handler500 in Django? - python

I have tried using https://docs.djangoproject.com/en/dev/topics/http/views/ tutorial, but still I am getting the standard 404 html page. I want to switch in to my custom view
handler404 = 'myview.views.custom_page_not_found' ,
I did debug it (using eclipse), then the value of handler404(old value -'django.config.default.views.page_not_found) is changed to the new value I have given ('myview.views.custom_page_not_found'). But it's still showing the older 404 page. And I have changed settings.py DEBUG into False then it shows the custom page. But it got some disadvantages (it won't load static files and all, DEBUG = false is not the right way) so I had to reset to True.
Do I have to make some other modification for implementing this?

I think you can not change the 404 page in DEBUG = True mode without difficulty.
There is a hint in the documentation (https://docs.djangoproject.com/en/dev/topics/http/views/#the-404-page-not-found-view):
If DEBUG is set to True (in your settings module), then your 404 view will never be used, and your URLconf will be displayed instead, with some debug information.

Try adding this to the bottom of your main urls.py:
if settings.DEBUG:
urlpatterns += patterns('',
(r'^404/$', TemplateResponse, {'template': '404.html'}))
Swap out the 404.html to the appropriate template you use, I believe 404.html is the default though. Then with debug=True you can test out your 404 page.
If you want to Test it out with Debug=True then you need this at the bottom of your main urls.py instead:
#Enable static for runserver with debug false
from django.conf import settings
if settings.DEBUG is False: #if DEBUG is True it will be served automatically
urlpatterns += patterns('',
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),
)
When running with DEBUG = False, don't forget to collect static:
python manage.py collectstatic
Hope this helps, Cheers!

Related

Django Custom error page's giving error

I'm trying to make custom error page general 404 and 500.
I'm not trying to raise just making a default if it happens for a user, but every place I'm trying to search and follows a tutorial and so on I always ends up in getting an internal error on both 500 and 404
I'm running django=1.11.6, and I'm running debug False because I need to see if it work of course.
How can I fix this issue and make it work?
And how can I make it so it also gives the user the error text so they can send it to me?
Views.py (In my app folder)
# Error Handlers
def handler404(request):
return render(request, 'handlers/404.html', status=404)
def handler500(request):
return render(request, 'handlers/500.html', status=500)
Urls.py (in my main config folder)
from django.conf.urls import include, url, handler404, handler500
from django.contrib import admin
handler404 = 'staff.views.handler404'
handler500 = 'staff.views.handler500'
urlpatterns = [
url(r'^', include('staff.urls')),
url(r'^admin/', admin.site.urls),
]
Firstly, you don't need custom handlers if you just want to use your own templates - just put your own 404.html and 500.html files in your root templates directory.
Secondly, rather than getting users to send you the error codes manually, you can configure Django to send you errors by email.

Value of settings.DEBUG changing between settings and url in Django Test

I'm trying to set up test for some URLS that are set only in debug. They are not set because apparently the value of DEBUG change to False between my setting file and urls.py. I've never encountered this problem before, and I don't remember doing anything particularly fancy involving DEBUG value.
Here's my urls.py :
from django.conf import settings
from my_views import dnfp
print "settings.DEBUG in url: {}".format(settings.DEBUG)
if settings.DEBUG:
urlpatterns += [url(r'^dnfp/$', dnfp, name="debug_not_found_page"...
Here's my setting file :
DEBUG=True
print "DEBUG at the end of the settings: {}".format(DEBUG)
The content that fail in my test :
reverse("debug_not_found_page"),
Here's the output of the test :
DEBUG at the end of the settings: True
settings.DEBUG in url: False
Creating test database for alias 'default'...
.E
(...)
NoReverseMatch: Reverse for 'debug_not_found_page' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
If I change the value myself in urls.py the url is set again and the test works with this urls.py :
from django.conf import settings
from my_views import dnfp
settings.DEBUG = True
if settings.DEBUG:
urlpatterns += [url(r'^dnfp/$', dnfp, name="debug_not_found_page"...
Any ideas when and why my value for DEBUG is changing between settings and urls ?
From the docs
Regardless of the value of the DEBUG setting in your configuration file, all Django tests run with DEBUG=False. This is to ensure that the observed output of your code matches what will be seen in a production setting.
The problem with your code is you are setting DEBUG = True after this line
urlpatterns += [url(r'^dnfp/$', dnfp, name="debug_not_found_page"
The reason is that all the URLs are already appended to urlpatterns[] and you are setting it after the appending of URLs and while appending the URL Django actually transfer control to urls.py for syntax validation purpose. That's why you are getting different value in urls.py.
Set value of DEBUG before this line
Try this, hope it will work.
You can use another approach for doing this, create a separate app for all these type of URLs and don't add the app to INSTALLED_APPS on the basis of debug variable.

custom handler404 => standard error page

When I try to use my own view for error 404, I instead get a standard error page. So, what I've done by now:
# root settings.py
DEBUG = False
ALLOWED_HOSTS = [
'*'
]
# blog urls.py
handler404 = 'views.custom_404'
# blog views.py
def custom_404(request):
return HttpResponse("Hello world, I'm a custom error 404")
And, besides, to try it locally on Django test server, I run it like this:
python manage.py runserver --insecure
But what I get when I go to some page which does not exist is:
Not Found
The requested url blablabla
So, for some reason I do not see my own message Hello world, I'm a custom error 404.
404 handlers are not per app, they can only be set from the main urls.py.

Django Development - Admin CSS file 404

I'm using this guide to attempt to get this working. Basically, I'm exploring django 1.6 (with python 2.7.6 on Mac OS X Yosemite beta), still working with the stock development server. I'm trying to include a CSS file to override some styles in the admin area. I have a static folder in my project root. My settings.py is completely stock (that means I have DEBUG set to true and that I'm using django.contrib.staticfiles). Inspecting the source and request/response reveals that I'm calling for the CSS file at my expected path, but that I'm getting a 404 when attempting to load it. I also get a 404 when attempting to hit the CSS file directly in the browser. I've searched google and SO and have not, as of yet, been able to find an answer.
The requested CSS file:
http://*mysite*/static/admin/css/mysite-admin.css
The file system path to the CSS file:
*myprojectdir*/static/admin/css/mysite-admin.css
Yes it won't work because Django does not serve by default static assets, in order to have static assets served (mind though this should be the case only for local dev) in your main urls.py file add this to the top:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
And then at the end of your urls.py:
if settings.DEBUG:
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', # NOQA
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
) + staticfiles_urlpatterns() + urlpatterns
Make sure you have defined STATIC_URL, MEDIA_ROOT and MEDIA_URL in your settings.py, for development STATIC_ROOT IS NOT needed.

variables included in TEMPLATE_CONTEXT_PROCESSORS not in template with DEBUG=False

When I set DEBUG=False in my settings file in django 1.5, I no longer have access to the STATIC_URL or any of the other variables that should be loaded by my TEMPLATE_CONTEXT_PROCESSORS in my django templates. Oddly, everything works when DEBUG=True. For what its worth, I definitely have 'django.core.context_processors.static' in my TEMPLATE_CONTEXT_PROCESSORS so that is not the issue. I have also checked a few other variables in my template context and none of the other nothing seems to be there. MEDIA_URL? nope. request? nope. See this example on github (which has been updated with solution), but these are the important pieces that correctly work when DEBUG=True and throw a 500 error when DEBUG=False:
# settings.py
from django.conf.global_settings import *
# ...
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
)
# believe it or not, 'django.core.context_processors.static' is in there
print TEMPLATE_CONTEXT_PROCESSORS
# views.py
from django.template import RequestContext
from django.shortcuts import render_to_response
def wtf(request):
return render_to_response(
"wtf.html", {},
context_instance=RequestContext(request)
)
Does something special happen in django 1.5 when you turn off debug mode? Any suggestions for fixing and/or debugging the problem would be greatly appreciated!
Looks like there was a change between Django 1.2 and 1.3.
You now have to include django.core.context_processors.static in your TEMPLATE_CONTEXT_PROCESSORS if you want the STATIC_URL available to your template outside of debug mode.
You also need to ensure you're using a RequestContext instance when rendering the template.
This can be fixed by editing the ALLOWED_HOSTS variable in your settings.py. See this answer for more details.
To get this to work on localhost, for example, set ALLOWED_HOSTS = ['localhost'].

Categories

Resources