Blog

How does Django handle error pages

Django Error pages come in several different varieties but can be broken down as follows:

  • 404 - page not found
  • 500 - server error
  • 403 - permission denied
  • 400 - bad request

When Django can’t find a regex matching the requested URL, or when an exception is raised, Django will invoke an error-handling view.

The views to use for these cases are specified by four variables. Their default values should suffice for most projects, but further customization is possible by overriding their default values.

Such values can be set in your root URLconf. Setting these variables in any other URLconf will have no effect.

Values must be callables, or strings representing the full Python import path to the view that should be called to handle the error condition at hand.

The variables are:

Another way 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. NOTE: The one caveat to this is you can only display a static page if you are dyanamically pulling in headers and footers then this solution will not work for you. 

Django has a progression it goes through in determining how it will display 404 errors:

If handler404 is present then it will use it's callable view to display the error page. 

If 404.html is present at top level of template tree it will use that template to display error page

If settings.DEBUG is "True" then it will use the debugging template to display error page

If none of the above is true then it will simply display a blank page with generic text such as:

Not Found

The requested URL / was not found on this server.

 

Default views

handler400

handler400¶

A callable, or a string representing the full Python import path to the view that should be called if the HTTP client has sent a request that caused an error condition and a response with a status code of 400.

By default, this is 'django.views.defaults.bad_request'. If you implement a custom view, be sure it returns anHttpResponseBadRequest.

See the documentation about the 400 (bad request) view for more information.

 

handler403

handler403¶

A callable, or a string representing the full Python import path to the view that should be called if the user doesn’t have the permissions required to access a resource.

By default, this is 'django.views.defaults.permission_denied'. If you implement a custom view, be sure it returns anHttpResponseForbidden.

See the documentation about the 403 (HTTP Forbidden) view for more information.

 

handler404

handler404¶

A callable, or a string representing the full Python import path to the view that should be called if none of the URL patterns match.

By default, this is 'django.views.defaults.page_not_found'. If you implement a custom view, be sure it returns anHttpResponseNotFound.

See the documentation about the 404 (HTTP Not Found) view for more information.

 

handler500

handler500¶

A callable, or a string representing the full Python import path to the view that should be called in case of server errors. Server errors happen when you have runtime errors in view code.

By default, this is 'django.views.defaults.server_error'. If you implement a custom view, be sure it returns anHttpResponseServerError.

See the documentation about the 500 (HTTP Internal Server Error) view for more information.

 

 

 

Introduction

When you need to obtain a file from your user you will need to provide the ability to upload it in your web site. The following is a straight away manner of doing that but I am not sure if it will work on PyPE servers but it works locally so you might say it is a proof of concept.

models.py

In your models file you will create a model that will tie your backend SQL database  to the uploaded file. In this example the file will actually not reside in the database but within the file structure of your project. Note the FileField below contains an upload_to path. This indicates the file will be uploaded to a directory and if no directory exists it will create the directory of file/%Y/%m/%d with %Y being current year, %m being current month and %d being current day so the path might look like file/2011/3/1/filename.

Update models.py file as shown:

from django.db import models

\# Create your models here.

\# \**************************************************************************\* #

class MyModel(models.Model):
    file = models.FileField(upload_to='file/%Y/%m/%d', )#storage=DocRepoStorage()
    name = models.CharField(max_length=100,)

    class Meta:
        db_table = 'Mymodel'

forms.py

Obviously we need a form for our webpage and the easiest way to get it there is to use a ModelForm which takes as input the model and converts it to a form without the developer having to code each individual field. For our rexample model that would have been hard but this approach means you could change your model and not have to recode your form.

from django.forms import ModelForm
from user_bm6432.docapp.dapp.models import MyModel

class MyForm(ModelForm):
    class Meta:
    model = MyModel

template (test.html)

Next we need to get our form onto our template to display to the user. Our template has a form that we code but then just contains the variable "form" that has been created in our view.

{{utd_header}}
HEY I'm test.html
<br/><br/>
{{abc}}
<form method='post' action='' enctype='multipart/form-data' >
{% csrf_token %}
<table>
{{form}}
</table>
&nbsp; <input>
</form>

{{utd_footer}}

settings.py

We also need to make changes to our settings.py file to include our backend database. In this case that would be a sqlite3 database. Also note that MEDIA_ROOT and MEDIA_URL have been defined as pointing to a local directory in our project called 'static'. CURRENT_DIR provides the absolute path to the static directory no matter where the project is being run from. 

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # 'django.db.backends.mysql' or
                                                # 'django.db.backends.oracle' or
                                                # 'django.db.backends.sqlite3'
        'NAME': 'database/db_basicapp', # Or path to database file if using sqlite3.
        'USER': '',                             # Not used with sqlite3.
        'PASSWORD': '',                         # Not used with sqlite3.
        'HOST': '',                             # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                             # Set to empty string for default. Not used with sqlite3.
        }
}

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))

\# Absolute path to the directory that holds media.
\# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(CURRENT_DIR, 'static')

\# URL that handles the media served from MEDIA_ROOT. Make sure to use a
\# trailing slash if there is a path component (optional in other cases).
\# Examples: "[http://media.lawrence.com|http://media.lawrence.com/]", "[http://example.com/media/|http://example.com/media/]"
MEDIA_URL = '/apps/user_bm6432/docapp/static/'

views.py

The views.py has been updated to include a view function called index that is pointed to by our urlconf module and it handles the http request. If the request is a GET then it just displays the template which has the form we defined above. If the request is a POST then it will take the request including any files that were selected in the form and push them back through the form "MyForm" to create an instance. If the form is valid we then save it which will cause really to things to happen and that is for the file to be written to the file structure currently within our project although it could point to another location outside our project. It will also cause a record to be created in our database. The "file" field in our database will contain the path to the file. In our case it would be file/%y/%M/%d/filename.

from django.shortcuts import render_to_response, redirect
from django.core.context_processors import csrf
from utdirect.templates import UTDirectContext

from user_bm6432.docapp.dapp.forms import MyForm
from user_bm6432.docapp.dapp.models import MyModel

defaults = {
    'window_title': 'University of Texas/Basic UT Direct Application',
    #'css_file': \['/apps/user_bm6432/basicapp/static/basic.css',\],
\#    'js_file': \['1.js', '2.js'\],&nbsp; # create and put js files here
    'api_key': '8B54A49X54',
    }

def index(request):
    if request.method == 'POST':
        form = MyForm(request.POST, request.FILES)
        if form.is_valid():
            print 'form valid'
            a = form.save()
        else:
            print 'not valid', form.errors


    context = {}
    form = MyForm()
    context\['form'\] = form
    context\['abc'\] = 'index'
    context.update(csrf(request))
    return render_to_response('test.html',UTDirectContext(request, context, defaults=defaults))

...

 Introduction

models.py

Update models.py file as shown:

from django.db import models

 # Create your models here.

 # *************************************************************************** #

 class MyModel(models.Model):
     file = models.FileField(upload_to='file/%Y/%m/%d', )#storage=DocRepoStorage()
     name = models.CharField(max_length=100,)

     class Meta:
         db_table = 'Mymodel'

forms.py

from django.forms import ModelForm
 from user_bm6432.docapp.dapp.models import MyModel

 class MyForm(ModelForm):
     class Meta:
         model = MyModel

template (test.html)

{{utd_header}}
 HEY I'm test.html
 <br/><br/>
 {{abc}}
 <form method='post' action='' enctype='multipart/form-data' >
 {% csrf_token %}
 <table>
 {{form}}
 </table>
   <input>
 </form>

 {{utd_footer}}

settings.py

DATABASES = {
     'default': {
         'ENGINE': 'django.db.backends.sqlite3', # 'django.db.backends.mysql' or
                                # 'django.db.backends.oracle' or
                                # 'django.db.backends.sqlite3'
         'NAME': 'database/db_basicapp', # Or path to database file if using sqlite3.
         'USER': '',            # Not used with sqlite3.
         'PASSWORD': '',        # Not used with sqlite3.
         'HOST': '',            # Set to empty string for localhost. Not used with sqlite3.
         'PORT': '',            # Set to empty string for default. Not used with sqlite3.
     }
 }

 # Absolute path to the directory that holds media.
 # Example: "/home/media/media.lawrence.com/"
 MEDIA_ROOT = os.path.join(CURRENT_DIR, 'static')

 # URL that handles the media served from MEDIA_ROOT. Make sure to use a
 # trailing slash if there is a path component (optional in other cases).
 # Examples: "http://media.lawrence.com", "http://example.com/media/"
 MEDIA_URL = '/apps/user_bm6432/docapp/static/'

views.py

from django.shortcuts import render_to_response, redirect
 from django.core.context_processors import csrf
 from utdirect.templates import UTDirectContext

 from user_bm6432.docapp.dapp.forms import MyForm
 from user_bm6432.docapp.dapp.models import MyModel

 defaults = {
     'window_title': 'University of Texas/Basic UT Direct Application',
     #'css_file': ['/apps/user_bm6432/basicapp/static/basic.css',],
 #    'js_file': ['1.js', '2.js'],  # create and put js files here
     'api_key': '8B54A49X54',
     }

 def index(request):
     if request.method == 'POST':
         form = MyForm(request.POST, request.FILES)
         if form.is_valid():
             print 'form valid'
             a = form.save()
         else:
             print 'not valid', form.errors


     context = {}
     form = MyForm()
     context['form'] = form
     context['abc'] = 'index'
     context.update(csrf(request))
     return render_to_response('test.html',UTDirectContext(request, context, defaults=defaults))

 

Introduction

models.py
Update models.py file as shown:from django.db import models

# Create your models here.

# *************************************************************************** #

class MyModel(models.Model):
    file = models.FileField(upload_to='file/%Y/%m/%d', )#storage=DocRepoStorage()
    name = models.CharField(max_length=100,)

    class Meta:
        db_table = 'Mymodel'

forms.py
from django.forms import ModelForm
from user_bm6432.docapp.dapp.models import MyModel

class MyForm(ModelForm):
    class Meta:
        model = MyModel

template (test.html)
{{utd_header}}
HEY I'm test.html
<br/><br/>
{{abc}}
<form method='post' action='' enctype='multipart/form-data' >
{% csrf_token %}
<table>
{{form}}
</table>
  <input type="submit">
</form>

{{utd_footer}}

//

settings.py
 DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # 'django.db.backends.mysql' or
                               # 'django.db.backends.oracle' or
                               # 'django.db.backends.sqlite3'
        'NAME': 'database/db_basicapp', # Or path to database file if using sqlite3.
        'USER': '',            # Not used with sqlite3.
        'PASSWORD': '',        # Not used with sqlite3.
        'HOST': '',            # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',            # Set to empty string for default. Not used with sqlite3.
    }
}

 # Absolute path to the directory that holds media.
 # Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(CURRENT_DIR, 'static')

 # URL that handles the media served from MEDIA_ROOT. Make sure to use a
 # trailing slash if there is a path component (optional in other cases).
 # Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/apps/user_bm6432/docapp/static/'