My project is named homefood, and when I runserver I get this error.Anybody have any clue how to fix this error.
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in homefood.urls, Django tried these URL patterns, in this order:
^foodPosts/
^admin/
The current URL, , didn't match any of these.
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.
My settings.py file looks like this…
import dj_database_url
"""
Django settings for homefood project.
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_ROOT = 'staticfiles'
# SECURITY WARNING: keep the secret key used in production secret!
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*'] # Allow all host headers
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django.contrib.sites',
'foodPosts',
'registration',
'profiles',
'homefood',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'homefood.urls'
WSGI_APPLICATION = 'homefood.wsgi.application'
#= dj_database_url.config()
#'default': dj_database_url.config(default='mysql://localhost')}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_db',
'USER': 'root',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}#= dj_database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/New_York'
USE_I18N = True
USE_L10N = True
USE_TZ = True
#Django-registration additions, for account registration
ACCOUNT_ACTIVATION_DAYS=7
EMAIL_HOST = 'localhost'
EMAIL_PORT = 102
EMAIL_HOST_USERNAME = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
DEFAULT_FROM_EMAIL = 'testing@example.com'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
) #static asset configuration
and my urls.py in my homefood folder is
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'homefood.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^foodPosts/',include('foodPosts.urls')),
url(r'^admin/', include(admin.site.urls)),
)
I think my problem is either in my urls.py, or my settings.py but I am unsure. Any help would be greatly appreciated. Thanks.
-
Getting Help
-
el
-
es
-
fr
-
id
-
it
-
ja
-
ko
-
pl
-
pt-br
-
zh-hans
- Language: en
-
1.8
-
1.10
-
1.11
-
2.0
-
2.1
-
2.2
-
3.0
-
3.1
-
3.2
-
4.0
-
4.1
-
dev
-
Documentation version:
4.2
Built-in Views¶
Several of Django’s built-in views are documented in
Writing views as well as elsewhere in the documentation.
Serving files in development¶
-
static.
serve
(request, path, document_root, show_indexes=False)¶
There may be files other than your project’s static assets that, for
convenience, you’d like to have Django serve for you in local development.
The serve()
view can be used to serve any directory
you give it. (This view is not hardened for production use and should be
used only as a development aid; you should serve these files in production
using a real front-end web server).
The most likely example is user-uploaded content in MEDIA_ROOT
.
django.contrib.staticfiles
is intended for static assets and has no
built-in handling for user-uploaded files, but you can have Django serve your
MEDIA_ROOT
by appending something like this to your URLconf:
from django.conf import settings from django.urls import re_path from django.views.static import serve # ... the rest of your URLconf goes here ... if settings.DEBUG: urlpatterns += [ re_path( r"^media/(?P<path>.*)$", serve, { "document_root": settings.MEDIA_ROOT, }, ), ]
Note, the snippet assumes your MEDIA_URL
has a value of
'media/'
. This will call the serve()
view,
passing in the path from the URLconf and the (required) document_root
parameter.
Since it can become a bit cumbersome to define this URL pattern, Django
ships with a small URL helper function static()
that takes as parameters the prefix such as MEDIA_URL
and a dotted
path to a view, such as 'django.views.static.serve'
. Any other function
parameter will be transparently passed to the view.
Error views¶
Django comes with a few views by default for handling HTTP errors. To override
these with your own custom views, see Customizing error views.
The 404 (page not found) view¶
-
defaults.
page_not_found
(request, exception, template_name=‘404.html’)¶
When you raise Http404
from within a view, Django loads a
special view devoted to handling 404 errors. By default, it’s the view
django.views.defaults.page_not_found()
, which either produces a “Not
Found” message or loads and renders the template 404.html
if you created it
in your root template directory.
The default 404 view will pass two variables to the template: request_path
,
which is the URL that resulted in the error, and exception
, which is a
useful representation of the exception that triggered the view (e.g. containing
any message passed to a specific Http404
instance).
Three things to note about 404 views:
- The 404 view is also called if Django doesn’t find a match after
checking every regular expression in the URLconf. - The 404 view is passed a
RequestContext
and
will have access to variables supplied by your template context
processors (e.g.MEDIA_URL
). - If
DEBUG
is set toTrue
(in your settings module), then
your 404 view will never be used, and your URLconf will be displayed
instead, with some debug information.
The 500 (server error) view¶
-
defaults.
server_error
(request, template_name=‘500.html’)¶
Similarly, Django executes special-case behavior in the case of runtime errors
in view code. If a view results in an exception, Django will, by default, call
the view django.views.defaults.server_error
, which either produces a
“Server Error” message or loads and renders the template 500.html
if you
created it in your root template directory.
The default 500 view passes no variables to the 500.html
template and is
rendered with an empty Context
to lessen the chance of additional errors.
If DEBUG
is set to True
(in your settings module), then
your 500 view will never be used, and the traceback will be displayed
instead, with some debug information.
The 403 (HTTP Forbidden) view¶
-
defaults.
permission_denied
(request, exception, template_name=‘403.html’)¶
In the same vein as the 404 and 500 views, Django has a view to handle 403
Forbidden errors. If a view results in a 403 exception then Django will, by
default, call the view django.views.defaults.permission_denied
.
This view loads and renders the template 403.html
in your root template
directory, or if this file does not exist, instead serves the text
“403 Forbidden”, as per RFC 9110#section-15.5.4 (the HTTP 1.1
Specification). The template context contains exception
, which is the
string representation of the exception that triggered the view.
django.views.defaults.permission_denied
is triggered by a
PermissionDenied
exception. To deny access in a
view you can use code like this:
from django.core.exceptions import PermissionDenied def edit(request, pk): if not request.user.is_staff: raise PermissionDenied # ...
The 400 (bad request) view¶
-
defaults.
bad_request
(request, exception, template_name=‘400.html’)¶
When a SuspiciousOperation
is raised in Django,
it may be handled by a component of Django (for example resetting the session
data). If not specifically handled, Django will consider the current request a
‘bad request’ instead of a server error.
django.views.defaults.bad_request
, is otherwise very similar to the
server_error
view, but returns with the status code 400 indicating that
the error condition was the result of a client operation. By default, nothing
related to the exception that triggered the view is passed to the template
context, as the exception message might contain sensitive information like
filesystem paths.
bad_request
views are also only used when DEBUG
is False
.
Back to Top
Writing views¶
A view function, or view for short, is a Python function that takes a
web request and returns a web response. This response can be the HTML contents
of a web page, or a redirect, or a 404 error, or an XML document, or an image .
. . or anything, really. The view itself contains whatever arbitrary logic is
necessary to return that response. This code can live anywhere you want, as long
as it’s on your Python path. There’s no other requirement–no “magic,” so to
speak. For the sake of putting the code somewhere, the convention is to
put views in a file called views.py
, placed in your project or
application directory.
A simple view¶
Here’s a view that returns the current date and time, as an HTML document:
from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
Let’s step through this code one line at a time:
-
First, we import the class
HttpResponse
from the
django.http
module, along with Python’sdatetime
library. -
Next, we define a function called
current_datetime
. This is the view
function. Each view function takes anHttpRequest
object as its first parameter, which is typically namedrequest
.Note that the name of the view function doesn’t matter; it doesn’t have to
be named in a certain way in order for Django to recognize it. We’re
calling itcurrent_datetime
here, because that name clearly indicates
what it does. -
The view returns an
HttpResponse
object that
contains the generated response. Each view function is responsible for
returning anHttpResponse
object. (There are
exceptions, but we’ll get to those later.)
Django’s Time Zone
Django includes a TIME_ZONE
setting that defaults to
America/Chicago
. This probably isn’t where you live, so you might want
to change it in your settings file.
Mapping URLs to views¶
So, to recap, this view function returns an HTML page that includes the current
date and time. To display this view at a particular URL, you’ll need to create a
URLconf; see URL dispatcher for instructions.
Returning errors¶
Django provides help for returning HTTP error codes. There are subclasses of
HttpResponse
for a number of common HTTP status codes
other than 200 (which means “OK”). You can find the full list of available
subclasses in the request/response
documentation. Return an instance of one of those subclasses instead of a
normal HttpResponse
in order to signify an error. For
example:
from django.http import HttpResponse, HttpResponseNotFound def my_view(request): # ... if foo: return HttpResponseNotFound("<h1>Page not found</h1>") else: return HttpResponse("<h1>Page was found</h1>")
There isn’t a specialized subclass for every possible HTTP response code,
since many of them aren’t going to be that common. However, as documented in
the HttpResponse
documentation, you can also pass the
HTTP status code into the constructor for HttpResponse
to create a return class for any status code you like. For example:
from django.http import HttpResponse def my_view(request): # ... # Return a "created" (201) response code. return HttpResponse(status=201)
Because 404 errors are by far the most common HTTP error, there’s an easier way
to handle those errors.
The Http404
exception¶
- class django.http.Http404¶
When you return an error such as HttpResponseNotFound
,
you’re responsible for defining the HTML of the resulting error page:
return HttpResponseNotFound("<h1>Page not found</h1>")
For convenience, and because it’s a good idea to have a consistent 404 error page
across your site, Django provides an Http404
exception. If you raise
Http404
at any point in a view function, Django will catch it and return the
standard error page for your application, along with an HTTP error code 404.
Example usage:
from django.http import Http404 from django.shortcuts import render from polls.models import Poll def detail(request, poll_id): try: p = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404("Poll does not exist") return render(request, "polls/detail.html", {"poll": p})
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
.
When DEBUG
is True
, you can provide a message to Http404
and
it will appear in the standard 404 debug template. Use these messages for
debugging purposes; they generally aren’t suitable for use in a production 404
template.
Customizing error views¶
The default error views in Django should suffice for most web applications,
but can easily be overridden if you need any custom behavior. Specify the
handlers as seen below in your URLconf (setting them anywhere else will have no
effect).
The page_not_found()
view is overridden by
handler404
:
handler404 = "mysite.views.my_custom_page_not_found_view"
The server_error()
view is overridden by
handler500
:
handler500 = "mysite.views.my_custom_error_view"
The permission_denied()
view is overridden by
handler403
:
handler403 = "mysite.views.my_custom_permission_denied_view"
The bad_request()
view is overridden by
handler400
:
handler400 = "mysite.views.my_custom_bad_request_view"
Testing custom error views¶
To test the response of a custom error handler, raise the appropriate exception
in a test view. For example:
from django.core.exceptions import PermissionDenied from django.http import HttpResponse from django.test import SimpleTestCase, override_settings from django.urls import path def response_error_handler(request, exception=None): return HttpResponse("Error handler content", status=403) def permission_denied_view(request): raise PermissionDenied urlpatterns = [ path("403/", permission_denied_view), ] handler403 = response_error_handler # ROOT_URLCONF must specify the module that contains handler403 = ... @override_settings(ROOT_URLCONF=__name__) class CustomErrorHandlerTests(SimpleTestCase): def test_handler_renders_template_response(self): response = self.client.get("/403/") # Make assertions on the response here. For example: self.assertContains(response, "Error handler content", status_code=403)
Async views¶
As well as being synchronous functions, views can also be asynchronous
(“async”) functions, normally defined using Python’s async def
syntax.
Django will automatically detect these and run them in an async context.
However, you will need to use an async server based on ASGI to get their
performance benefits.
Here’s an example of an async view:
import datetime from django.http import HttpResponse async def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
You can read more about Django’s async support, and how to best use async
views, in Asynchronous support.
Page Not Found
If you try to access a page that does not exist (a 404 error), Django directs you to a built-in view that handles 404 errors.
You will learn how to customize this 404 view later in this chapter, but
first, just try to request a page that does not exist.
In the browser window, type 127.0.0.1:8000/masfdfg/
in the address bar.
You will get one of two results:
1:
2:
If you got the first result, you got directed to the built-in Django 404
template.
If you got the second result, then DEBUG
is
set to True
in your settings, and you must set it to False
to get directed to
the 404 template.
This is done in the settings.py
file, which
is located in the
project folder, in our case the my_tennis_club
folder,
where you also have to specify the host name from where your project runs from:
Example
Set the debug property to False
, and allow the project to run from your local
host:
my_tennis_club/my_tennis_club/settings.py
:
.
.
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
.
.
Important: When DEBUG = False, Django requires you to specify the hosts you will allow this
Django project to run from.
In production, this should be replaced with a proper domain name:
ALLOWED_HOSTS = ['yourdomain.com']
In the browser window, type
127.0.0.1:8000/masfdfg/
in the address bar, and you will get the built-in 404 template:
Customize the 404 Template
Django will look for a file named 404.html
in the
templates
folder, and display it when there is a 404 error.
If no such file exists, Django shows the «Not Found» that you saw in the
example above.
To customize this message, all you have to do is to create a file in the templates
folder and name it
404.html
, and fill it with whatever you
want:
my_tennis_club/members/templates/404.html
:
<!DOCTYPE html>
<html>
<title>Wrong address</title>
<body>
<h1>Ooops!</h1>
<h2>I cannot
find the file you requested!</h2>
</body>
</html>
In the browser window, type
127.0.0.1:8000/masfdfg/
in the address bar, and you will get the customized 404 template:
If you are developing a web application, then most probably you will come across situations where you need to show the 404 (not found) page. We will talk about this in this article.
When you should return 404
It is a good practice to use a 404 page in cases when users are accessing the wrong URLs, for instance, when the link you used to access the page is broken. We will also talk about how to use the right status code for this situation. You should return 404 HTTP error if one of the following is true:
- The page does not exist.
- The requested page was deleted.
- Page not found.
Python Django provides a number of functions to customize the 404 page. Using them you can easily configure your 404 page without having to write a new view function. Let’s have a look at how to return a 404 error in Django.
First, import Http404
from django.http
module. Next, raise
the Http404
exception within your view. For example, here is views.py
file for the view which always returns 404:
from django.http import Http404 def not_found(req): raise Http404
Remember to route the not_found
view. To do it, write the following to urls.py
:
from . import views from django.urls import path urlpatterns = [ # ...your other routes... path('nowhere/', views.not_found), # for 404 demo ]
You should not do this in production apps. We do it now just for the sake of demonstration. Now, restart your application. If you go to the routed URL /nowhere/
, you will see one of the following:
- If you have
DEBUG=True
set insettings.py
you will see Django app traceback. - Otherwise, you will see the 404 error template you specified in
settings.py
ortemplates/404.html
Using get_object_or_404 function
Sometimes you need to retrieve a model from a database and return 404 error if the model does not exist. Of course, you can use an if-else statement, but you can use a shortcut, get_object_or_404 function. See the code example below:
from django.shortcuts import get_object_or_404, render # example model - use models.py to create one from app.models import Page def get_page(req, page_id): page = get_object_or_404(Page, id=page_id) return render(req, 'app/page.html', { 'text': page.text })
We used an imaginary template ‘app/page.html’, which renders the text
variable we passed. If the Page
model with id page_id
does not exists, Django will return the 404 not found error.
Conclusion
To return 404 in Django Framework, you should include the Http404
exception and raise
it within a view function. Also you can use get_object_or_404
function from django.shortcuts
if you retrieve a model from a database in your view. You learned how to return 404 error and get it handled correctly.