Implementing http404 in django - django

Implementing page not found in django and have looked at the documentation 404
I do not get a page not found error as yet what ami doing here
In my code in urls i have done the following,
url(r'^$', 'site_config.views.pagenotfound')
from django.http import Http404
def pagenotfound(request):
return render_to_response('polls/pagenotfound.html', {})

The way you handle 404 and 500 in django is: by default, in the templates directory, create a 404.html
If you need a custom handler, just add these to urls.py
handler404 = 'views.page_not_found_custom'
handler500 = 'views.page_error_found_custom'
design the 404.html page the way you want

Related

angular django rewrite unmatched urls to index.html (angular app)

I have a django server and an angular app.
I am able to launch the angular app and navigate to the various parts of the site using links i have added to the app.
But if I want to go to a part of the site directly I get a 404 error.
example if I have a link in my app that directs me to
niftysite.com/team
it works
but if I put in my browsers url
niftysite.com/team
it fails with 404
I understand this is because the default behavior is to look for the link to the page in the servers urls.
I also understand that the fix is to have server side 404s redirect to the angular index.html page with the route params included.
My question is how?
I have already started on an implementation but I am not sure how to fix it. Any guidance the rest of the way through would be helpful.
here is what I have so far.
urls.py
handler404 = views.error_404
views.py
from django.shortcuts import render
def error_404(request):
data = {}
return render(request, 'index.html', data)
similar to this question, but I am not using Nginx
How to redirect 404 requests to homepage in Django single page app using Nginx?
Here is the implementation:
urls.py
url(r'^.*$', views.PassToAngular.as_view())
make sure this url is the last url in your urls array.
views.py
from django.shortcuts import render
from django.views.generic import TemplateView
class PassToAngular(TemplateView):
def get(self, request, **kwargs):
return render(request, 'index.html', context= None)
thanks to MihirKavatkar for your help!

Django 1.9 broken redirect after custom 404 page

On Django 1.9 multilingual site domain.com/ used to redirect to domain.com/en/ automatically.
Now, when I put a custom 404.html in top level templates dir, Django no longer redirects to the language:
domain.com/ throws server error 500 instead of redirecting to domain.com/en/
How keep custom 404 error page and get no server error 500?
Code:
urls:
from django.conf.urls import url, include
from django.contrib import admin
from django.http import HttpResponse
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
url(r'^robots\.txt$', lambda r: HttpResponse(" ", content_type="text/plain"))
]
urlpatterns += i18n_patterns(
url(r'^admin/', admin.site.urls),
url(r'^rosetta/', include('rosetta.urls')),
url(r'^', include('mp.urls', namespace='mp', app_name='mp')),
)
Dirs:
- project_folder
- app
-- templates
--- app_name
---- all templates
--- 404.html (had to put higher than app subdir, for Django to see it)
- project
-- settings, etc
view:
class Main(View):
def get(self, request):
c = get_seo_stuff("home")
t = "app/home.html"
return render(request, t, c)
def post(self, request):
pass
Code is pretty simple and it used to work just before the 404.html commit.
Figured it out. It was a multisite Django installation, and when I added a custom 404.html in one app, Django tried showing it on other apps as well.
The 404.html contained urls and stuff, not resolvable from the other tenant apps, resulting in Server Error 500.
Solution: add custom 404 handlers or use neutral 404.html page.

How can I return a 404 error page when user hits a wrong url in django?

Hi I have the urls like the following, here if the user hits urls which are not in my urls.py file then I need to return a 404 Error page how to do it?
urlpatterns = patterns(
'',
url(r'login$', auth.onLogin),
url(r'logout$', auth.onLogout),
......
)
Can anyone tell me how to do it?
You need just prepare 404.html template and set DEBUG=False in your settings.py
Or if you want a custom 404 page, you just need to set the 404 handler adding in your main urls.py :
handler404 = 'mysite.views.my_custom_404_view'
https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
Create a 404.html file in your template folder
add this code to your view
from django.shortcuts import render
def handler404(request):
return render(request, ’404.html’)
and in urls.py
handler404 = ‘mysite.views.handler404′

Django 404 pages return 200 status code

I'm going through the Django tutorial and am on part 5: Testing. I run into the problem where I'm using the DetailView and ListView "shortcut" views to factor out code (as suggested by the tutorial), but when a 404 page is displayed, a 200 status code is returned instead. Am I doing something wrong? The tutorial says the status code should be 404.
Thanks!
You need to define the Http header to have a 404 status.
return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404)
It is important to inform the search engines that the current page is a 404. Spammers sometimes creates lots of urls that could seem that would lead you to some place, but then serves you another content. They frequently make lots of different addresses serve you almost the exact same content. And because it is not user friendly, most SEO guide lines penalize that. So if you have lots of addresses showing the same pseudo-404 content, it could not look good to the crawling systems from the search websites. Because of that you want to make sure that the page you are serving as a custom 404 has a 404 status.
If you are trying to make a custom 404 page, here it is a good way to go:
Into your application's urls.py add:
# Imports
from django.conf.urls.static import static
from django.conf.urls import handler404
from django.conf.urls import patterns, include, url
from yourapplication import views
##
# Handles the URLS calls
urlpatterns = patterns('',
# url(r'^$', include('app.homepage.urls')),
)
handler404 = views.error404
Into your application's views.py add:
# Imports
from django.shortcuts import render
from django.http import HttpResponse
from django.template import Context, loader
##
# Handle 404 Errors
# #param request WSGIRequest list with all HTTP Request
def error404(request):
# 1. Load models for this view
#from idgsupply.models import My404Method
# 2. Generate Content for this view
template = loader.get_template('404.htm')
context = Context({
'message': 'All: %s' % request,
})
# 3. Return Template for this view + Data
return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404)
The secret is in the last line: status=404
Hope it helped!
I look forward to see the community inputs to this approach. =)
You can
return HttpResponseNotFound(render_to_string('404.html'))
instead.

Django display 404 on missing template

I have a website where some pages are edited by hand. When one of those templates is missing, it just means that the page is not present, so I would like to display an Error 404.
Instead I get an exception TemplateDoesNotExist.
Is there a way to tell Django to display an error 404 whenever it does not find a template?
If you want this behaviour for all views on your site, you might want to write your own middleware with a process_exception method.
from django.template import TemplateDoesNotExist
from django.views.defaults import page_not_found
class TemplateDoesNotExistMiddleware(object):
"""
If this is enabled, the middleware will catch
TemplateDoesNotExist exceptions, and return a 404
response.
"""
def process_exception(self, request, exception):
if isinstance(exception, TemplateDoesNotExist):
return page_not_found(request)
If you have defined your own handler404 you would need to replace page_not_found above. I'm not immediately sure how you could convert the string handler404 into the callable required in the middleware..
To enable your middleware, add it to MIDDLEWARE_CLASSES in settings.py. Be careful of the position where you add it. The standard Django middleware warning applies:
Again, middleware are run in reverse order during the response phase, which includes process_exception. If an exception middleware returns a response, the middleware classes above that middleware will not be called at all.
put the return of the response in the view (or whereever the template is rendered) in a try-except block:
from django.http import Http404
from django.shortcuts import render_to_response
from django.template import TemplateDoesNotExist
def the_view(request):
...
try:
return render_to_response(...)
except TemplateDoesNotExist:
raise Http404
Off the top of my head, but if you set DEBUG=False in your settings, won't you get a 404 then on every error (including TemplateNotFound)?