Spring 2013 COSI Project Page

Clarkson University Residence Life Staff ( CURLS )



Django .: the web framework for perfectionalists with deadlines.

Object Relational Mapper

Utilize the power of OOP and define that data that you want for your website in Python classes, and let Django take care of the rest.
class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()
                        

MVC vs. MTV

Model View Controller (MVC) is a software architecture pattern which separates the representation of information from the user's actions with it. The 'model' consists of application data, business rules, logic, and functions. A 'view' can be any arbitrary representation of the underlying data (i.e. HTML). The 'controller' mediates input, converting it into commands for the model or view.
Model Template View (MTV) is more alone the lines of how Django does things. Although both patterns are extremely similar, Django argues that a 'view' represents what data you see, not necessarily how it is represented to you. Furthermore, Django considers a 'controller' to be the actual framework itself. For more on this read this.

Automatic Admin Interface

Save yourself the time of adding an interface to update the website content securely, and simply enable the admin in a few simple steps. See [Enable Admin].

Elegant URL design

Wire up your websites URL domains to your defined controller functions with simple and clean regular expressions.
from blog.controllers import *
urlpatterns = patterns('',
    url(r'^blog/$', 'blog.controllers.index'),
    url(r'^blog/page(?P\d+)/$', 'blog.controllers.page'),
)            
                        

Template System

Utilize Django's easy, extensible, and fluid template system to make the design work of your views easier.
{% extends "base_generic.html" %}

{% block title %}{{ section.title }}{% endblock %}

{% block content %}
<h1>{{ section.title }}</h1>

{% for story in story_list %}
<h2>
  <a href="{{ story.get_absolute_url }}">
      {{ story.headline|upper }}
  </a>
</h2><p>{{ story.tease|truncatewords:"100" }}</p>
{% endfor %}
{% endblock %}                        
                        

... and much more @ https://www.djangoproject.com/

Django Tuts .: [From Scratch], [Setup DB], [Enabling Admin], [Django-Social-Auth]

Let's start with a simple example to show just how easy it is to get a baseline Django site up and running.

1) You will need to download and install Django, you can get the latest stable version from here.

Then at a terminal unpack and install:
tar xzvf Django-*.*.*.tar.gz
cd Django-*.*.*
sudo python setup.py install

2) As long as all was well with the installation, we can start building some web apps. First, start a new project:

django-admin.py startproject testsite

NOTE: take note of the directory structure that is created by this command. Django is designed to be modular in the sense that we create our "project" which is the base file structure for our new website to live, and each significant functionality that we are going to pack into our site is considered a new "app" to Django. To help us decide what should be apps and what should be projects, the makers of Django offer this:

"What's the difference between a project and an app? An app is a Web application that does something - e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects."

So we have this notion of modularity and reusability following the DRY principle, thus we should design our apps to be pluggable to reuse later in other websites if necessary.

3) Now, what can we do with our newly created project? For starters lets run the darn thing:

python manage.py runserver

Navigate to 'localhost:8000' in your favorite web browser, and you should see "It worked! Congratulations on your first Django powered page." As the page suggests, this is the bare bones structure and no true content is in our site yet.

NOTE: the 'runserver' command first up the development Python web server that comes packaged with Django. Please heed the documentation when moving from development to production and don't use the development server for production. Find out more here. Furthermore, the development server can take optional arguments to tell it to answer to specific IP addresses and port numbers. ( i.e by issuing 'python manage.py runserver 192.168.1.100:8080' we can make our website live to our LAN )

4) Let's recap. In 3 steps, we have downloaded and installed Django, created a new project ( website ), and served that base website off of a server. That was easy, and FAST!

Where to go from here: check out [Setup DB], [Enable Admin], [MVC Architecture]

Let's give our website some actual data to back it up! Django is configurable with all sorts of database backends, the easiest of which to setup is the sqlite3 which we are going to do here.

1) Make sure you are in the root of the project ( i.e. /path/to/testsite/ ), open up testsite/settings.py in your favorite editor and navigate to the 'DATABASES' dictionary:

DATABASES = {
        'default': {
                    'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
                    'NAME': '',                      # Or path to database file if using sqlite3.
                                                     # The following settings are not used with sqlite3:
                    'USER': '',
                    'PASSWORD': '',
                    'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
                    'PORT': '',                      # Set to empty string for default.
        }
}
                                        

2) We are using sqlite3 in this tutorial, so just as the comment says: append 'sqlite3' to the 'ENGINE' value as so:

DATABASES = {
        'default': {
                    'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
                    'NAME': '',                      # Or path to database file if using sqlite3.
                                                     # The following settings are not used with sqlite3:
                    'USER': '',
                    'PASSWORD': '',
                    'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
                    'PORT': '',                      # Set to empty string for default.
        }
}
                                        

3) Next, we need to tell Django where our database is going to live. I like to take the proactive approach ( because we want our site to work no matter where we download and run it off of ) so we are going to do a little markup to allow us to provide Django a failsafe way of finding our database. Add the following just above the 'DATABASES' dictionary:

import os
PROJ_ROOT = os.path.abspath(os.path.dirname(__file__))
DATABASES = {
        'default': {
                    'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
                    'NAME': '',                      # Or path to database file if using sqlite3.
                                                     # The following settings are not used with sqlite3:
                    'USER': '',
                    'PASSWORD': '',
                    'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
                    'PORT': '',                      # Set to empty string for default.
        }
}
                                        

3.5) Once that is pointing Django to our database is simple. Add the folling for the 'NAME' value as so:

import os
PROJ_ROOT = os.path.abspath(os.path.dirname(__file__))
DATABASES = {
        'default': {
                    'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
                    'NAME': os.path.join(PROJ_ROOT, 'testsite.db'),                      # Or path to database file if using sqlite3.
                                                     # The following settings are not used with sqlite3:
                    'USER': '',
                    'PASSWORD': '',
                    'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
                    'PORT': '',                      # Set to empty string for default.
        }
}
                                        

4) Save the edits to testsite/settings.py, and then issue the following at the cmd prompt:

python manage.py syncdb

That command will create our new database with the settings we just configured, follow the prompts to create the admin user and remember the credentials for when it comes time to enable the Admin suite.

Where to go from here: check out [Enabling Admin], [MVC Architecture]

So, you have a base site setup, and now you are really wanting some of that easy CMS style management of your site. Well Django thought of that for you :). The best part is Django comes pre-packaged with a full fledged Admin suite that is a breeze to setup. We are going to do that now using the 'testsite' project from [From Scratch].

Prereq: We need to have our database configured before we proceed. If you don't already have that setup go to [Setup DB] first.

1) Make sure you are in the root of the project ( i.e. /path/to/testsite/ ), and open up testsite/settings.py in your fav editor and navigate to the 'INSTALLED_APPS' tuple

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

2) Just like the comment says, we need to uncomment the line 'django.contrib.auth' so that Django will recognize that we want the admin app to be a part of our site:

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

3) Next we need to add the url configurations for the admin app to our site, open up testsite/urls.py in an editor and uncomment the following lines:

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

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'testsite.views.home', name='home'),
    # url(r'^testsite/', include('testsite.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)),
)
                                        

4) Lastly, we just need to comment the models from the admin suite to our local database:

python manage.py syncdb

5) Test that the admin suite is rolling by navigating to 'localhost:8000/admin/' in your brower. If all went well you should be presented with a login prompt to the admin suite. Go ahead and login and check out your new admin functionality on your website.

Where to go from here: check out [MVC Architecture], [Django-Social-Auth]

With the ever increasing social media and enourmous web presence of the human population as a whole as developers we have a lot of resources and information about our users available for us to us in our applications. A most import resource, and one that should never be taken lightly, are our users authentication credentials. If we take a minute to think from a user standpoint, when you go to a new website that wants to maintain information pertainent to you, the easiest thing that site can do is allow you to 'login' with your credentials that you have already created elsewhere, such as Facebook, Github, etc. From a developer standpoint this is a great, and extremely encouraged, approach to implementing 'Users' of our websites. Let's offload the liability and grunt work of trying to roll our own security system, and simply interface with an existing API provided from a trusted 3rd party source instead. We are going to do just that in this tutorial using the amazing Django package 'django-social-auth'. The source can be found on Github here, and a great set of thorough documentations about this package can be found here.

Prereq) This tutorial assumes you have a base site setup, with a database configured and the Admin suite up and running, check previous tutorials if you have questions.

1) We need to download the package and install it:

git clone git://github.com/omab/django-social-auth.git
cd django-social-auth
sudo python setup.py install

2) Add 'social_auth' to your 'INSTALLED_APPS' dictionary in testsite/settings.py:

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

3) Commit the models for 'social_auth' to your local database:

python manage.py syncdb

4) We need to add in our desired authentication backend in our settings file, by default the settings file doesn't contain this tuple but it is located in the global settings of Django, thus add the following to your settings.py file in order to simply append our desired authentication backend to the existing tuple:

from django.conf import global_settings
AUTHENTICATION_BACKENDS = global_settings.AUTHENTICATION_BACKENDS + (
    'social_auth.backends.contrib.github.GithubBackend',
)                                        
                                        

5) Next, we need to add 'social_auth's urls to our site's url configuration in testsite/urls.py:

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

    url(r'', include('social_auth.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)),
)
                                        

6) The next step is to obtain an API ID and and API secret key from Github. You can do so by going to the 'Application' section in your account settings and registering your application by its domain. Once you grab those two things we need to insert them into our settings.py file as such ( I have X'd mine out here):

# github settings
GITHUB_APP_ID = 'XXXXXXXXXXXX'
GITHUB_API_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'                                        
                                        

7) Next, add two more settings to the settings.py which are URL settings that the Github API will use when directing users back to your website ( I just set the URL's back to the root of testsite ):

LOGIN_URL          = '/'
LOGIN_REDIRECT_URL = '/'                                        
                                        

8) Now lets create a 'login.html' which is where we want our users to utilize this login functionality. Create a directory called 'templates' inside testsite/. Then create a baseline html file called 'login.html' inside templates/, here is mine:


<html>
        <body>
            <a href="{% url "socialauth_begin" "github" %}">Login with Github</a>
        </body>
</html>

                                        

)

9) Now we need to create a controller function that will serve up our login.html, so in views.py:

from django.shortcuts import render_to_response

def login_user( request ):
        return render_to_response( 'login.html' )                                        
                                        

10) And last, but very important, lets wire up a url to the controller we just created. In testsite/urls.py:

                                        
from controllers import *
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'testsite.views.home', name='home'),
    # url(r'^testsite/', include('testsite.foo.urls')),

    url( r'^$', controllers.login_user ),
    url(r'', include('social_auth.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)),
                                        

11) That's it, go to your login page and click the button :)

C U R L S .: Clarkson University Residence Life Staff

Source: all of the source code for this project is on Github.

Demo: demo is live here.

Purpose: to create a web application to be used by Clarkson University's Residence Life staff, with the intent of helping members meet their numerous responsibilities more efficiently. This project has manifested out of personal desires to help relieve even a small portion of stress from myself and fellow staff members. Having now been a part of Clarkson's Residence Life for six semesters I have a workable knowledge of all tiers of the "chain of command" and feel that a web application that is tailored to assist staff members in communicating about a more centralized work environment would prove to be quite useful.

Features:

  • Case Management: cooperative tracking of resident case files
  • Documentation Management: weeekly reports, program write-ups, incident reports, etc.
  • Cooperative Program Planning: staff can work together to plan and manage programs and events.
  • Centralized Staff Calendar: duty schedules, mandatory events, programs, etc.

Planning:

Contributors:

This site powered by Bootstrap