Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
NEW SERVER - 11.9.2020 ... Retiring, March 2020 - sorry, you have missed our final public course.
The Coronavirus situation has lead us to suspend public training - which was on the cards anyway, with no plans to resume

Please ask about private 'maintenance' training for Python, Tcl, Perl, PHP, Lua, etc
Happily continuing private consultancy / programming work
 
Complete set of Django files
The Django web framework example from a Well House Consultants training course
More on The Django web framework [link]

This example is described in the following article(s):
   • Nesting Templates in Django - [link]
   • Demonstration of a form using Django - [link]
   • Sessions (Shopping Carts) in Django - the Python Web Framework - [link]

This example references the following resources:
http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
http://media.lawrence.com/media/
http://media.lawrence.com/static/
http://foo.com/static/admin/
http://docs.djangoproject.com/en/dev/topics/logging

Source code: z_complete Module: Y306
# Complete set of Django files for "staff / team" demonstrations

settings.py - django server settings
urls.py - routing of URLs
models.py - definition of database tables, relationships and business logic
views.py - View Controllers - how incoming data is saved to model, and model is viewed
mybasepage.html - Template on which most other views are based
index.html - home page specific template elements
single.html - single record specific template elements
formdemo.html - Form and session demosntration - the template

#------------------------------------------------------------
#--------------------------------- settings.py
#------------------------------------------------------------

# Django settings for training project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Graham Ellis', 'graham@wellho.net'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'trainingdata.sq3', # 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.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Dublin'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-ie'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '3=pl)_y8&%w+_lu)r)w1zn1^o2na%d2m#g#q21fzl8fnv5lh%v'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'training.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
        "/Users/grahamellis/dpy/djxi/training/templates"
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'staff',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

#------------------------------------------------------------
#--------------------------------- urls.py
#------------------------------------------------------------

from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'training.views.home', name='home'),
    # url(r'^training/', include('training.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),

    url(r'^team/?$', 'staff.views.index'),
    url(r'^team/index.html?$', 'staff.views.index'),
    url(r'^team/test.html?$', 'staff.views.testing'),
    url(r'^team/formdemo.html?$', 'staff.views.formdemo'),

    url(r'^team/(?P<jobtype>\w+)\.htm', 'staff.views.single'),
)

#------------------------------------------------------------
#--------------------------------- staff/models.py
#------------------------------------------------------------

from django.db import models

class Role(models.Model):
        name = models.CharField(max_length=24)
        required = models.IntegerField()

        def __unicode__ (self):
                return self.name + " (" + str(self.required) + ")"

class People(models.Model):
        name = models.CharField(max_length=64)
        role = models.ForeignKey(Role)
        hours = models.FloatField()
        hobbies = models.TextField()

        def __unicode__ (self):
                return self.name + " (" + str(self.role) + ")"

#------------------------------------------------------------
#--------------------------------- staff/views.py
#------------------------------------------------------------

# OK - so it's really my controller ;-)

from staff.models import People, Role
from django.http import HttpResponse

from django.template import Context, loader
from django.shortcuts import render_to_response

from django.core.context_processors import csrf
from django import forms

def index(request):

        pageshell = loader.get_template('staff/index.html')

        html = ''
        for role in Role.objects.all():
                html += '<a href="' + role.name + '.html">' + role.name + "</a><br />"

        fill = Context({'year': '2012',
                'mainbody': html,
                'copyright': "Well House"})

        return HttpResponse(pageshell.render(fill))

def single(request,jobtype):

        people = []
        for person in People.objects.filter(role__name__iexact=jobtype):
                people.append([str(person)])

        fill = Context({'year': '2012',
                'role': jobtype,
                'clist': people,
                'copyright': "Well House"})

        return render_to_response('staff/single.html',fill)

def describe(element,word):
        html = word + ":<br />"
        for pair in element.items():
                html += pair[0] + " --> " + str(pair[1]) + "<br />"
        html += "<br />"
        return html

def testing(request):

        html = "Here are your passed in values<br /><br />"
        html += "get_host() " + request.get_host() + "<br />"
        html += "method " + request.method + "<br />"
        html += "raw_post_data " + request.raw_post_data + "<br />"
        html += "path " + request.path + "<br />"
        html += "path_info " + request.path_info + "<br /><br />"

        # Next are QueryDict Objects
        html += describe(request.GET,"GET")
        html += describe(request.POST,"POST")
        html += describe(request.REQUEST,"REQUEST")
        html += describe(request.COOKIES,"COOKIES")
        html += describe(request.FILES,"FILES")
        html += describe(request.META,"META")

        # for key in dir(request):
        # html += key + "> " + "<br />"

        return HttpResponse(html)

class MyForm(forms.Form):
        role = forms.CharField(max_length=20)
        count = forms.IntegerField()

def formdemo(request):
        havesubmission = "Blank form"
        stufftosave = ""
        if request.method == 'POST':
                form = MyForm(request.POST)
                if form.is_valid():
                        havesubmission = "We HAVE got data to store"
                        stufftosave = "Saving ... " + form.cleaned_data['role']
                        stufftosave += ": " + str(form.cleaned_data['count'])

                        adding = request.session.get("newroles","")
                        adding += form.cleaned_data['role'] + " " + str(form.cleaned_data['count']) + "<br />"
                        request.session["newroles"] = adding

                        form = MyForm()
                else:
                        havesubmission = "Data Invalid - please correct"
        else:
                form = MyForm()

        myHistory = ""
        for retained_key in request.session.keys():
                myHistory += retained_key + " -> " + str(request.session[retained_key]) + "<br />"
        havesubmission += "<br /><br />History ...<br />" + myHistory

        mycontext = {'formholder': form, 'status': havesubmission, 'saving': stufftosave}
        mycontext.update(csrf(request))
        return render_to_response('staff/formdemo.html',mycontext)

#------------------------------------------------------------
#--------------------------------- templates/staff/mybasepage.html
#------------------------------------------------------------

<html>
<head>
<title>Staff Stuff</title>
</head>
<body bgcolor=#FFEEDD><h1>Staff Information {% block pagetitle %} Page Name {% endblock %}</h1>
{% block tagline %} What this is {% endblock %}<br />
{% block mainsection %} The Real McCoy {% endblock %}
<hr />
Copyright {{copyright}} in year {{year}}
</body>
</html>

#------------------------------------------------------------
#--------------------------------- templates/staff/index.html
#------------------------------------------------------------

{% extends "staff/mybasepage.html" %}
{% block pagetitle %}Index{% endblock %}
{% block tagline %}Here are the various Roles, matey!{% endblock %}
{% block mainsection %}{{mainbody|safe}}{% endblock %}

#------------------------------------------------------------
#--------------------------------- templates/staff/single.html
#------------------------------------------------------------

{% extends "staff/mybasepage.html" %}
{% block pagetitle %}[{{role}}]{% endblock %}
{% block tagline %}Here are you colleagues in that area{% endblock %}
{% block mainsection %}
{% for colleague in clist %}
        &bull; How about asking {{colleague.0}}<br />
{% endfor %}
<hr />Please select <a href=index.html>EAR</a> for the Eindex
{% endblock %}

#------------------------------------------------------------
#--------------------------------- templates/staff/formdemo.html
#------------------------------------------------------------

<html>
<head>
<title>This is a form demo</title>
</head>
<body bgcolor=#CCBBAA>
<h1>Form Demo</h1>
<b>{{ status|safe }}</b><br /><br />
<form method="POST">
{% csrf_token %}
{{ formholder.as_p }}
<input type="submit" value="Submit" />
</form>
<hr />
{{ saving }}
</body>
</html>
Learn about this subject
This module and example are covered on our public %dj% course. If you have a group of three or more trainees who need to learn the subject, we can also arrange a private or on site course for you.

Books covering this topic
Yes. We have over 700 books in our library. Books covering Python are listed here and when you've selected a relevant book we'll link you on to Amazon to order.

Other Examples
This example comes from our "The Django web framework" training module. You'll find a description of the topic and some other closely related examples on the "The Django web framework" module index page.

Full description of the source code
You can learn more about this example on the training courses listed on this page, on which you'll be given a full set of training notes.

Many other training modules are available for download (for limited use) from our download centre under an Open Training Notes License.

Other resources
• Our Solutions centre provides a number of longer technical articles.
• Our Opentalk forum archive provides a question and answer centre.
The Horse's mouth provides a daily tip or thought.
• Further resources are available via the resources centre.
• All of these resources can be searched through through our search engine
• And there's a global index here.

Purpose of this website
This is a sample program, class demonstration or answer from a training course. It's main purpose is to provide an after-course service to customers who have attended our public private or on site courses, but the examples are made generally available under conditions described below.

Web site author
This web site is written and maintained by Well House Consultants.

Conditions of use
Past attendees on our training courses are welcome to use individual examples in the course of their programming, but must check the examples they use to ensure that they are suitable for their job. Remember that some of our examples show you how not to do things - check in your notes. Well House Consultants take no responsibility for the suitability of these example programs to customer's needs.

This program is copyright Well House Consultants Ltd. You are forbidden from using it for running your own training courses without our prior written permission. See our page on courseware provision for more details.

Any of our images within this code may NOT be reused on a public URL without our prior permission. For Bona Fide personal use, we will often grant you permission provided that you provide a link back. Commercial use on a website will incur a license fee for each image used - details on request.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2020: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/resources/ex.php4 • PAGE BUILT: Mon Sep 28 10:27:35 2020 • BUILD SYSTEM: JelliaJamb