I've investigated how to create an error page such as 404 Not Found, so I'll summarize it.
I will touch on the following error codes.
Under any templates directory,
Place. Then, when the target error is thrown, the template will be read automatically.
myproject
- myapp
- urls.py
- views.py
- models.py
- app.py
- forms.py
- templates
- 403.html
- 404.html
- 500.html
Implement your own 404 page etc. as below.
404.html
{% extends "base.html" %}
{% block content %}
<section>
<div>
<label>404 Not Found<br>The page you are looking for could not be found.<br><a class="hover-under" href="{% url 'top' %}">Back to top page</a></label>
</div>
</section>
{% endblock %}
These pages will be returned if you call an exception for which each status code should be returned.
404 Not Found
Raise the Http404
class inside the django.http
package.
views.py
from django.http import Http404
class MyView(View):
def index(self):
raise Http404
403 Forbidden
There is a PermissionDenied
class in django.core.exceptions
.
views.py
from django.core.exceptions import PermissionDenied
class MyView(View):
def index(self):
if not self.request.user.is_authenticated:
raise PermissionDenied
500 Internal Server Error Use a normal error that doesn't catch or explicitly returns something that would result in a normal InternalServerError, such as a syntax error.
views.py
from .models import Example
class MyView(View):
def index(self):
try:
_instance = Example.objects.get(id=1)
except Example.DoesNotExists:
#Throw an exception (usually don't do much)
raise Exception
Recommended Posts