How to link django to my own 404 error page? - python

Normaly django looks for a url in url.py file...
if it finds it load the relevent HTML page and if it doesn't find it shows:
Page not found (404) with the msg:
You're seeing this error because you have DEBUG = True in your Django
settings file. Change that to False, and Django will display a
standard 404 page.
I want to change standard 404 page that django shows. I have a HTML page that I created PageNotFound.html I want django to show everytime there is a Page not found (404) when DEBUG = False. How do I do that?

In order to show customized HTML when Django returns a 404, you can create an HTML template named 404.html and place it in the top level of your template tree. This template will then be served when DEBUG is set to False.
https://docs.djangoproject.com/en/dev/topics/http/views/#the-404-page-not-found-view
Also, there is an useful section "Customizing error views".
And in the case you want to test your template withour turning DEBUG=False, you can run manage.py runserver --insecure.
It will force Django to serving static files with the staticfiles app even if the DEBUG setting is False. But note that it it only for local development and could be insecure. You can read more about this option here.

Here is a quote from the Django doc:
This template should be called 404.html and located in the top level of your template tree.
Check here for the full text; for non 1.8 doc it should be somewhere around here: Writing views > Returning errors > The Http404 exception.

You should create following view:
def custom404(request):
return render(request, '404.html', status=404)
And connect it with following construction in urls.py:
handler404 = 'path.to.views.custom404'

Related

Django 404 page not found

I've been doing a lesson on udemy trying to make a clone site of producthunt using django. I've tried asking there, but I don't get an answer. For some reason when I run the exact same code as the instructor, I get an error when trying to load the page localhost:8000/signup or any other pages other than the home page.
I get this error:
error
Settings file:
settings
Main urls:
main urls
app urls (named accounts):
app urls
views:
app views
finally my file structure for reference:
directory
I've been trying to figure it out with no avail. Any help would be great thank you.
signup is a route in the accounts app. In your main urls.py you include your accounts.urls under accounts/. Putting that all together, with your current structure you should be hitting accounts/signup rather than just signup.
There's no url /signup in your web.
You're url is for accounts/signup/

Redirect example.com users to example.com/#/login

I am working on a project that uses Django and Angular. I do not have a background as a web developer so please try to explain your answer so that a novice person can understand it.
Basically I want to make it so that the login page is the default page instead of the index page.
I currently have the following url handler in my main Django project urls.py:
url(r'^$', 'core.views.generic.index')
I also have another urls.py in an app called core that sends visitors to the login page:
url(r'^/login$', private.MeLogin.as_view())
Now I want the login page to become the default page instead if the index page. How can I do that?
I have tried adding the following the the views file in the core app:
#login_required(redirect_field_name='', login_url='#/login')
def index(request):
return render_to_response('html/index.html', locals(), context_instance=RequestContext(request))
Unfortunately I get the message
This webpage has a redirect loop
I do not know how to solve this problem. Basically I want users to be redirected to the login page if they enter any URL that is not handled by other URL handlers. When they successfully log in they are redirected to a dashboard page automatically.
EDIT:
The login page URL is handled in the core urls.py file and points to a different view than index.
url(r'^/login$', private.MeLogin.as_view())
Web servers, in this case Django, do not see the fragment after the #. You are redirecting from / to /, creating a redirect loop.
If you want to redirect to the Django login url, you need login_url='/login'.
As an aside, you should remove the leading slash from your regex r'^/login$.
In #login_required(redirect_field_name='', login_url='#/login')
remove redirect_field_name='', it really is not neccessary and make sure that #/login in login_url='#/login is the same as in your url.py file:
like
views.py
#login_required(redirect_field_name='', login_url='accounts/login/')
as
url.py
url(r'^accounts/login/', auth_views.login),
I assume your Angular & Django apps are running in two seperate ports, like:
Django on port 8000
Angular on port 1000
So if you give /#/login it will redirect for the same with Django port (8000/#/login).
So why don't you give the full URL www.example.com/#/login?

CSS not rendered in custom template for 404 and 500 pages django 1.8

This is my folder structure
Music
-Music
-Feature
-static
-feature
core.css
-css
other css files
-js
-img
-templates
404.html
500.html
index.html
-feature
about.html
detail.html
template.html
manage.py
views.py
from django.shortcuts import render
def error404(request):
return render(request,'404.html')
urls.py
urlpatterns = [
url(r'^featured/(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^about/$', views.about, name='about'),
url(r'^FAQ/$', views.faq, name='faq'),
]
handler404 = 'mysite.views.error404'
The custom 404.html file gets rendered but with no css.And normally the css works fine on other pages but when I set debug=falseto check the custom 404 error page in settings.py the css for the entire project disappears. Something to do with folder structure or some other problem?
edit: core.css is the main css file and the part with other css files contains css for plugins
It's about serving static files. When you use DEBUG = True then django takes care about them otherwise your server should do it. Django in debug mode uses this view. The warning from there:
This view will only work if DEBUG is True.
That’s because this view is grossly inefficient and probably insecure.
This is only intended for local development, and should never be used
in production.
You can run your server with --insecure option just to test 404 error or you can explicilty create url for that page to check its styling:
Use the --insecure option to force serving of static files with the
staticfiles app even if the DEBUG setting is False. By using this you
acknowledge the fact that it’s grossly inefficient and probably
insecure. This is only intended for local development, should never be
used in production and is only available if the staticfiles app is in
your project’s INSTALLED_APPS setting. runserver --insecure doesn’t
work with CachedStaticFilesStorage.
Your handler404 and view are okay. But you don't need them. Just a custom 404 template is enough. See: https://docs.djangoproject.com/en/1.8/topics/http/views/#the-http404-exception
In order to use the Http404 exception to its fullest, you should
create a template that is displayed when a 404 error is raised. This
template should be called 404.html and located in the top level of
your template tree.
The template is in the right location. I think the problem is serving your static files. Open developer tools in your browser to see what resources fail to load (console, network or sources tab). Inspect the paths. Is there an external style sheet link in the head section of the 404 source? (elements tab or view source code).
https://docs.djangoproject.com/en/1.8/howto/static-files/

Django 1.8 how to create my own 404 page?

i want to create my own 404 page.
In settings.py I have added:
DEBUG = TEMPLATE_DEBUG = False
ALLOWED_HOSTS = ['*',]
In urls.py:
handler404 = 'blog.views.handler404'
In views.py:
def handler404(request):
return render(request, 'blog/404.html')
Also I have created that 404.html file.
When i start server i write:
python manage.py runserver --insecure
--insecure is to provide static files (otherwise it is nonsense). But if i go non existing page i get:
<h1>Not Found</h1><p>The requested URL /post/9/ was not found on this server.</p>
How do I solve this?
I am using Django 1.8 dunno if this changes anything
You shouldn't need anything in urls.py. Go to your root views.py and add your handler404 method there, and leave urls.py alone.
Ref: Django, creating a custom 500/404 error page
Also, I don't see your TEMPLATE_DIRS variable, i.e.
TEMPLATE_DIRS = (
'/path/to/template/files/',
'/path/to/more/template/files/'
)
Need to make sure that your templates in ../blog/.. are getting found properly. Personally I'd add that specifically as a subdirectory.

Django handler404 not called on raise Http404()

When i override the handler404 and handler500 in my urls.py like so:
from myapp.views import not_found_view
handler404 = not_found_view
handler500 = not_found_view
and call raise Http404() in my middleware, i see my 404 page.
When i remove both handler404 and handler500 from my urls.py and raise Http404() in my middleware, i see my default 500 error page (from Django Suit) - hence the reason i'm trying to set a custom 404 template to be used on raise Http404()'s.
Now my problem: when i remove the handler500 and only set the handler404, i also get to see a HTTP 500 page! :|
Why is my handler500 called when i raise Http404() ??
I have multiple template directories in multiple apps, i tried placing a 404.html in my main app that contains the settings and in another 'normal' app but that didn't work..
I've set DEBUG to False as well.
Hope someone can answer my question!
You don't have to write your own handlers if you just want to replace Django's template. Django uses 404.html and 500.html files for templates and you can replace them with putting file with same name to the directory listed in settings.TEMPLATE_DIRS.
In your example that means that you can create myapp/templates/404.html and myapp/templates/500.html files.
Note that you have to set DEBUG to False to se those templates.
Check this article for mor details.
I ran into a similar situation. My custom handler404 WAS being called, yet my browser response showed the error500.
Upon inspection, I found I had a syntax error in the template. Thus, the 500 was being caused by that. I fixed the template and the result was as desired.
The catch 22 is that by default, template debug == debug, so if you set DEBUG=False then the template debug will be false as well; you'll see the 500 error without the template error trace.
So, place a print() statement in your handler404 view, right before returning render() . If you see the output in your django console, you'll know the error is in your template.
You could also try this in your settings.py (django 1.8+) but this didn't seem to work for me, and I didn't follow through once I fixed the template.
TEMPLATES = [
{
'OPTIONS': {
'debug': True,
}
},
The 404-page-not-found-view needs an "exception" argument:
def handler404(request, exception):
return render(request, 'customer/home_page/404.html', status=404)
Another solution is to replace (monkey-patch) Django's page_not_found.
from django.views import defaults
from myapp.views import not_found_view
defaults.page_not_found = not_found_view
Monkey-patching is bad practice and may stop working if Django updates internal API, but still may be useful in some situations. Ex. if other methods don't work on some reason.

Categories