Django 1.8 official document translation: 3-2-1 built-in view


Built in view

Several of Django’s built-in views are described in the authoring view and elsewhere in the document.

File server in development environment

static.serve(request, path, documentroot, showindexes=False)

In the local development environment, in addition to the static files in your project, there may be some files. For convenience, you want Django as the server. The serve () view can be used as a server for any directory. (this view cannot be used in the production environment, but should only be used for development assistance; in the production environment, you should use a real front-end web server to serve these files.).

The most common example is when users upload documents toMEDIA_ROOTYes.django.contrib.staticfilesIt is used for static files and does not process files uploaded by users, but you can make Django as media by adding some content to urlconf_ Root server:

from django.conf import settings
from django.views.static import serve

# ... the rest of your URLconf goes here ...

if settings.DEBUG:
    urlpatterns += [
        url(r'^media/(?P<path>.*)$', serve, {
            'document_root': settings.MEDIA_ROOT,

Note that the code snippet here assumes yourMEDIA_URLThe value of is'/media/'。 It will callserve()View, passing the path and from urlconf (required)document_rootParameters.

Because defining this URL pattern is a bit cumbersome, Django provides a small URL helper functionstatic(), it receivesMEDIA_URLSuch parameters are used as prefixes and view paths, such as'django.views.static.serve'。 Any other function parameters are passed transparently to the view.

Error view

Django native comes with several default views for handling HTTP errors. To overwrite them with your customized views, see customizing error views.

404 (page not found) view

defaults.pagenotfound(request, template_name=’404.html’)

When you trigger http404 in a view, Django will load a special view to handle 404 errors. Default todjango.views.defaults.page_not_found()View, which produces a very simple “not found” message or rendering404.htmlTemplate, if you created it in the root template directory.

The default 404 view will pass a variable to the template:request_path, which is the URL that caused the error.

Three points to note about view 404:

  • If Django does not find a match after detecting each regular expression in the urlconf, it will also call the 404 view.

  • The 404 view is passed aRequestContextAnd you can access variables provided by the template context processor (for exampleMEDIA_URL)。

  • If debug is set toTrue(in yoursettingsModule), then the 404 view will never be called, but your urlconf will be displayed with some debugging information.

500 (server error) view

defaults.servererror(request, templatename=’500.html’)

Similarly, if a runtime error occurs in the view code, Django will perform the behavior in a special case. If a view causes an exception, Django will call by defaultdjango.views.defaults.server_errorView, which produces a very simple “server error” message or rendering500.html, if you define it in your root template directory.

The default 500 view does not pass variables to500.htmlTemplate with an emptyContextTo render to reduce the possibility of errors again.

IfDEBUGSet toTrue(in yoursettingsModule), then the 500 view will never be called, but the backtrace will be displayed with some debugging information.

403 (HTTP Forbidden) view

defaults.permissiondenied(request, templatename=’403.html’)

Like the 404 and 500 views, Django has a view that handles 403 Forbidden errors. If a view results in a 403 view, Django will call by defaultdjango.views.defaults.permission_deniedView.

This view loads and renders files in your root template directory403.html, if the file does not exist, the “403 Forbidden” text is returned according to RFC 2616 (HTTP 1.1 specification).

django.views.defaults.permission_deniedadoptPermissionDeniedAbnormal trigger. To deny access to a view, you can use the View Code:

from django.core.exceptions import PermissionDenied

def edit(request, pk):
    if not request.user.is_staff:
        raise PermissionDenied
    # ...

400 (bad request) view

defaults.badrequest(request, templatename=’400.html’)

When Django raises aSuspiciousOperationIt may be processed through a component of Django (such as resetting session data). If there is no special processing, Django will think that the current request is a ‘bad request’ rather than a server error.

django.views.defaults.bad_requestAnd server_ The error view is very similar, except that it returns a 400 status code to indicate the operation of the error from the client.

bad_requestThe view is also only inDEBUGbyFalseWhen used.

translator:Django document collaborative translation team, Original:Built-in Views

In this paperCC BY-NC-SA 3.0Please keep the author’s signature and the source of the article.

Django document collaborative translation teamThere is a shortage of staff. Interested friends can join us. It is completely public welfare. Communication group: 467338606.

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]