Adding Custom 404 Page Not Found in Django

The posts that already exist can be seen in own detail pages. But what if some users want to try open the posts that doesn't exist, or maybe we had a post from past but we deleted it. However, some links can point this deleted post. In this case, we should use 404 page.

Let's try open the post that not exist with url link:

DoesNotExist Django

This is not what we want to show when the post doesn't exist. Open the views.py in the application called blog and import Http404:
from django.http import Http404
from django.shortcuts import render
from .models import Post

...

def detail(request, pk):
    try:
        post = Post.objects.get(pk=pk)
    except Post.DoesNotExist:
        raise Http404("There's nothing like that")
        
    context = {
        'post' : post,
    }
    return render(request, 'detail.html', context)
And that's what we got:
Page not found (404)

Also, Django provides short way for raising 404. This is a shortcut called get_object_or_404() and we can use it:
from django.shortcuts import render, get_object_or_404
from .models import Post

...

def detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    
    context = {
        'post' : post,
    }
    return render(request, 'detail.html', context)
That's okay, but how we can add our custom template for 404. I created 404.html file in templates, Django has already know this template for in its built-in views:
{% extends '_base_layout.html' %}

{% block content %}
<div class="row">
    <div class="col-sm-12">
        <div class="page">
            <h1>404 - Page Not Found</h1>
        </div>
    </div>
</div> 
{% endblock %}
But probably we can't see this custom page because of debug mode as true. Therefore, I'm going set DEBUG as false and after that ALLOWED_HOST should be changed like in the below:
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['*']
Now, let's check 404 page not found:
Custom 404 Page not found in Django

Finally, we got it. Also, we can give some style to this page via styles.css. Good work!

No comments:

Post a Comment