Django 404 pages return a 200 status code

I am reading a Django tutorial, and I'm on part 5: Testing. I ran into a problem when I use the DetailView and ListView shortcut to encode the code (as suggested in the tutorial), but when page 404 is displayed, the status code 200 is returned instead. Am I doing something wrong? The textbook says that the status code should be 404.

Thanks!

+4
source share
2 answers

You need to define the Http header in order to have the status 404.

return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404) 

It is important that search engines report that the current page is 404. Spammers sometimes create a lot of URLs that may seem to take you to some place, but then you will be presented with different content. They often make a lot of different addresses, and you get almost accurate content. And because it is not user friendly, most SEO search guides punish this. Therefore, if you have many addresses showing the same pseudo-404 content, this may not look good for crawling systems from search websites. Because of this, you want to make sure that the page that you use as a custom 404 has a status of 404.

If you are trying to create a custom 404 page, here is a good way:

In your urls.py application 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 

In your views.py application 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 this helps!

I look forward to the community contributing to this approach. =)

+4
source

You can

 return HttpResponseNotFound(render_to_string('404.html')) 

instead.

0
source

All Articles