My Journey in Python/Django – Hello World: Part 4 templates and GitHub

In earlier posts (Part 1 herePart 2 here and Part 3 here) I have set about building a “Hello World” Python/Django application. In this post I want to configure the first screen. So let’s get started…

I have already added a home module to the apps folder. The contents are:

models.py
tests.py
views.py

Nothing complicated I just want to add a routine to present an html page.

The Home page will be a subroutine – home. Here is the addition to the views.py file:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu

from django.shortcuts import render_to_response
from django.template import RequestContext

def home(request):

    context = {}

    return render_to_response(‘home/index.html’,
                              context,
                              RequestContext(request))

When we run localhost:8000 we get an error (totally expected!):

Page_not_found_at

Let’s fix that by updating urls.py:

    url(r’^$’, ‘apps.home.views.home’),

Another expected error (but it is progress). We are getting to the view.py file in the apps.home module because we are getting the error that no html file exists:

Templatedoesnotexist_at

In the Templates folder I create a home folder and create index.html in there:

cd templates
mkdir home

When I launch http://localhost:8000 I now get the index.html file loaded. Success!

Yes – we have a basic page but there is no formatting and we are not using any of the Django template features.

Let’s setup the base template. While we are at it we will probably need a set of include files so let’s create a folder for them.

cd templates
mkdir include

I then create a base.html file that will contain placeholders. 
<!doctype html>
<html class=”no-js” lang=”en”>
<head>
    <title>{% block pretitle %}{% endblock %}{% block title %}Hello World! {% endblock %}{% block posttitle %}{% endblock %}</title>

    <meta charset=”utf-8″>
    {% block head %}
    {% endblock %}

    {% block extra_head %}
    {% endblock %}
</head>

<body class=”{% block active_nav_tab %}{% endblock %}” {% block body_load_trigger %}{% endblock %}>
{% include “include/top-nav.html” %}

<div id=”page”>
    {% include “include/messages.html” %}

    {%block featureBox %}
    {% endblock %}

    {%block extra_body %}
    {% endblock%}

</div>

{% include “include/footer.html” %}

</body>
</html>

Note the use of block and endblock tags like these {% block block_name %}{% endblock %} in the code. These will be used in the application to insert customized code.

Now that we have a template we need to go back and update our index.html file to use this template.

We can include other template elements using the {% include “include/filename.html” %} tag. This allows us to break the template in to manageable chunks of code. It also makes it easier to produce variations of the basic template design.

With the base template in place we now need to edit the index.html home page to make use of the template.

First let’s take note of some of the sections in the template.

{% block pretitle %}{% endblock %}{% block title %}Hello World! {% endblock %}{% block posttitle %}{% endblock %}

This section allows us to insert a custom title for a page. If we want to replace the default Hello World! we need to use the {%block title}{{% endblock %} in our html file.

To add content to the main body of the page we can use the
    {%block featureBox %}
    {% endblock %}

section.

Let’s change Index.html so it still performs the same function but uses the base.html template. Here is the updated version:

{% extends “base.html” %}
{% block title %} Welcome to My World!{% endblock %}

{% block featureBox %}

{%load get_settings %}

@ekivemark

<p>Can we print the STATIC_URL SETTING: [ {{ STATIC_URL }} ]</p>

{% endblock %}

When we run this we get an error. This is because we didn’t create all of the include files. in this case

{% include “include/top-nav.html” %} 

and 

{% include “include/messages.html” %}

are the culprits. I create basic placeholders for those files and re-run the application and success! 

Welcome_to_my_world

We now have a simple template operational. At this stage with only a single page the template add a little overhead since we could code everything in a single file. But, when the application grows to tens or hundreds of pages the templates really shine because you can incorporate all the standard design elements in to the templates and your individual pages contain just the individualized elements. When you couple this with Cascading Stylesheets and the use of some standard design classes and you can quickly and easily modify the design of your application by making changes to your CSS files or to the template files.

Let’s demonstrate that by adding a simple horizontal line <hr /> to the top-nav and footer include files.

 

Welcome_to_my_world-1

Well that was easy!

So now we have a working application that is using the Django Template features. It may be time to check this code in to github. 
Let’s do that!

I navigate to the helloworld folder on my Mac (the one that contains manage.py).

git init
git status

git status tells me what files are being tracked.

git add README.md
git add *.py
git add apps
git add config
git add mainstatic
git add templates
git add .gitignore

run git status again to see that we haven’t missed anything. No – looks good.

Now let’s commit this to github:

git commit -m 'first commit'

git remote add origin https://github.com/ekivemark/helloworld.git git push -u origin master

Remember – you need to have an account on github. You will be prompted for your userid and password.

There we have the first stage completed. We have a do nothing application that uses Django templates and we have it stored in GitHub. 

We aren’t finished yet. The next step is to make sure Compass / SASS and Bootstrap are working. We will start out on that journey in the next post in this series.
Advertisements

Journey’s in Python/Django – Hello World Part 3

In the previous stages I have outlined the environment I am setting out to create for a starting point for Python/Django applications. I plan to post the default configuration to github. Before we get there we need to get a working basic application.

So far we have a python server that runs on our local machine but it does nothing. So let’s create a home page.

First I want to create an app folder to holds the code that supports the home page. To do that we can create a new app folder: home

In an earlier step I had created an apps folder. This is intended to hold the various apps or modules we create.

Let’s switch in to that folder. So starting from the helloworld folder that contains the manage.py file: 

cd apps

We can use a built in command to create the basic files that comprise an app. We will call our app “home”

python ../manage.py startapp home

This creates the following files in the “Home” folder under apps:

__init__.py
models.py
tests.py
views.py

Okay, so my first problem is that I have created an empty database file in db/db.db but when I do runserver Django tells me to make sure I set the information in the DATABASES setting. 

To work out what is going on I edit my settings.py and add a simple pair of print statements and re-run the server:

print “Base:”,BASE_DIR
print “Database:”,DBPATH

The console tells me the base folder is a third level of “helloworld”. Yes – I agree – very confusing. Let’s fix that.

I switch to the top level helloworld folder which contains:

bin
helloworld
include
lib

This is where my VirtualEnv is configured so I am going to rename the folder helloworld_env and add a readme.txt file to remind me to activate the VirtualEnv using 

source bin/activate

After trying to re-run the server things are not working. Time for a re-think. I believe VirtualEnv doesn’t like the folder renaming. 

So I decided to go to my PycharmProjects folder where I keep all my Python projects.  I create a virtualenv folder

mkdir virtualenv
cd virtualenv

I then re-create the helloworld application folder inside the virtualenv folder. 

virtualenv hw
cd hw
source bin/activate
pip install django

I copy the helloworld application structure in to the hw folder cd to the folder and runserver and we are back in business.

Now my folder structure reminds me I should be running a virtualenv.

Now my database file is still pointing to 2 levels of helloworld folder. That is still a little confusing. Time to rationalize the folder structure a little more.

The second level helloworld folder has these files:

__init__.py
settings.py
urls.py
wsgi.py

I decide to move these to the parent folder (the top level helloworld folder) and remove the helloworld sub-folder.

Trying to run the server and I get error message. Problems finding the settings file. I obviously need to make some configuration changes.

Manage.py:

Change:    os.environ.setdefault(“DJANGO_SETTINGS_MODULE”, “helloworld.settings”)
To:           os.environ.setdefault(“DJANGO_SETTINGS_MODULE”, “settings”)

Now it is not finding the helloworld.wsgi module.

settings.py:

Change: 
WSGI_APPLICATION = ‘helloworld.wsgi.application’
To:

WSGI_APPLICATION = ‘wsgi.application’

Change: 
ROOT_URLCONF = ‘
helloworld.urls’
To:

ROOT_URLCONF = ‘urls’

Back in business!

Quit the server and run

python manage.py syncdb

This creates the database.

Now let’s get the django admin working.

In settings enable the admin portal lines in the INSTALLED_APPS section:

    # Uncomment the next line to enable the admin:
    ‘django.contrib.admin’,

Add the following line after the STATIC_URL entry:

ADMIN_MEDIA_PREFIX = ‘/static/admin’

In urls.py make the following changes:

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

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

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

Now going to localhost:8000/admin should prompt you to enter a user id and password (the one you created when you ran the syncdb command.

We now have access to the administration tools.

We have accomplished quite a bit here. In the next post in this series I will actually look at getting the home page up and running.

#BMoreTechB: Baltimore Tech Breakfast

This morning on the last Wednesday of the month is Baltimore Tech Breakfast. This is the largest regular tech meetup in the Baltimore area.

624 Members of the Meetup. 

Hot News – Looking at starting a Columbia Tech Breakfast. Watch out for August!

Open Range Video: Cisco estimates that Internet video users will grow over next 4 years from just under 800 million to 1.6 Billion..

Macromoltek – Macromoltek.com

$806M and 15 years to bring a drug to market. 

6.5 years in Discovery, 8.5 years in development

Saving 10% saves significant time and money.

Macromoltek is developing computational tools to assist in drug discovery. Mathematical solutions to help the Biologic Therapeutics market. This is a fast growing (13%) market place.

Focused on Antibody and Antigen molecular simulations.

Their service provides back-end calculations. Also has a javascript tool to help visualize the simulations in a web browser.

The complex algorithms are written in C#. Took about 1 year to code using a team of 3. Architect, coder and scientific algorithm developer.

Hahler – Hahler.com

The social drinkers network. A virtual liquor store. 

@Hahlergirl 

This looks like Pinterest for alcohol. Twitter integration is built in.. 

This needs some Pinterest visual love. It could also do with some Geo Location input. Needs to be a mobile App a la Eatery.com.

Virtual “Send A Drink” is coming. Also contests. Instagram integration.

First focus is working out how to get people using the system.

How does Hahler handle age verification – uses Facebook and other sources.

Untapped is focused on craft beers. Hahler is more targeted to hard liquor and wine users.

80,000 drinks in the database. Proceeding with web development before going mobile.

Authntk – Authntk.com

Len Ostroff – CEO and Co-Founder

A social video marketing platform.

“Video is the new text”

Video is more engaging and convincing.

Authntk captures the customer’s passion.
92% of consumers trust earned media.

Create a campaign. Set controls over how long people can capture video for.  Allow users to upload a video or record with their webcam.

Also releasing a mobile video. This allows clients to capture their customer’s excitement at the point of engagement in the field.

Embed codes allow you to deploy video to any site (after video moderation by the client)

SAS business – pricing ranges from $80 – $400  per month.

Built on Amazon platform.

Next release will include download options so you can export your videos if you stop using the service.

Developing specific offerings for Automotive and Real Estate industries.

TeamGantt – http://TeamGantt.com

@NathanGilmore

A simple way to plan and manage a project.
Web based simple alternative to Microsoft Project.
Based around Task lists

MS-Project – Complicated, expensive and hard to share.

TeamGantt is simple, collaborative and web-based.
Offers iCal Outlook and Google Calendar integration.

Daily email updates.

Beta launch in November 2010. 

Not looking at Agile – Large number of companies still using Gantt charts for planning.

Currently have about 1000 customers – $10 – $79 per month.

FireJack Technologies – http://web.firejack.net

Benjamin Miller – CEO & Founder.

Platform as a Service offering – Open Flame Platform.

Open Flame supports Google, Twitter and Facebook login.

Build open deployable web applications that are mobile ready.

Automatically generates a RESTful API and documentation. Impressive!

Completely built on Open Source technologies.
$2,000 for annual license upwards. License for transaction volumes.

Also provides hosting.

The console is REST and SOAP enabled.

Provides Consulting services to allow people to go from concept to reality in under 30 days.

Terrance MacGregor – 

Commute Better Now!  Understand the true cost of your commute. 

Commuting has all sorts of impacts that are not put in to a value context.

Cowtrip has launched an ability to match users for carpooling.

Want to look at integration with job opportunities.

Developing the concept of a company dashboard. 
Android only App.

Suggestions from the audience: 
– Carpooling for kids – promote to schools?
– Link to real estate – promote concept of satellite offices.
– Integration for job sites.
– Carpooling for business parks (cross company integration)

Journey in Python/Django – Hello World – Part 2

Here are my ongoing adventures in configuring a base Python/Django application. 

First let’s give you some background on my development environment.
I am using a MacBook Air running Lion. 
I have Python 2.7 installed.
For my Python/Django editor I use the Jetbrains PyCharm IDE.
The first thing I want to do is to create a Hello World application on my local machine. I have a folder for all my PyCharm projects so I will create the application there.
So the first steps are with a Terminal Window:
– Change directory to my PYCharmProjects folder
mkdir helloworld 

The first thing I want to do is to isolate this application from modules used in other applications. For that we turn to VirtualEnv. Chris Scott has a great introduction on installing and configuring VirtualEnv.
After installing VirtualEnv I then proceeded to setup VirtualEnv with no dependency on the currently installed system site-packages for python. This is the default behavior for current releases of VirtualEnv but if you want to be explicit use this command:
virtualenv –no-site-packages helloworld
cd helloworld
source bin/activate
This activates VirtualEnv. You should see the system prompt add (helloworld) at the front of the prompt. One advantage of running in the VirtualEnv mode is that you don’t need to use sudo to make changes since you will only be changing this instance and not your base system configuration.
Since we are starting with a bare bones Python installation using Virtualenv we need to install all the modules we often forget about. Let’s start with the obvious one: django
pip install django
This lets me then run the startproject function of django-admin.py:
python bin/django-admin.py startproject helloworld
This will create a helloworld folder inside the existing helloworld folder.
– helloworld
— bin
— helloworld
   — helloworld
       —– settings.py
       —– urls.py
       —– wsgi.py
   — manage.py
— include
— lib
Let’s make sure we can run Python. 
cd helloworld
python manage.py runserver
if you see something like this then your python server is running on your local machine:
=========================================
Django version 1.4, using settings ‘helloworld.settings’
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
=========================================
By default your python server will run on 127.0.0.1 / localhost using port 8000
If you go to your browser and go to http://localhost:8000 or http://127.0.0.1:8000 you should see something like this:

Welcome_to_django
Great! We have a working server. We can shut it down for now and continue with our configuration efforts.
Go ahead and use CONTROL-C to quit the server.
While still in the helloworld/helloworld folder I now want to make a few folders to prepare our overall application structure:

mkdir apps
mkdir config
mkdir db
mkdir mainstatic

mkdir mainstatic/img
mkdir mainstatic/js

mkdir mainstatic/sass
mkdir mainstatic/stylesheets
mkdir templates

Next step is to fire up PyCharm and open up the helloworld/helloworld application.
Since we will be uploading this application to github we want to make sure any spurious files
are not included. The main thing here is to exclude any .pyc files and also the database. Our database will be stored here: db/db.db
To prepare for github we will create a .gitignore file in the helloworld/helloworld folder (alongside manage.py)
The .gitignore file contains the lines:

*.pyc
db/db.db

I also create a README.md file to store read me instructions for the app.
I also add a requirements.txt file in the config folder. This is used to record all of the modules installed that support this app. At the moment this has just one entry: django
The requirements.txt file is important. When you perform a fresh install of the application you can go to the helloworld folder that contains manage.py and issue the following command to install all the necessary modules:
sudo pip install -r config/requirements.txt 
As you add new modules make sure you keep this file up to date and add any configuration notes to the README.md markdown file.

Cascading Style Sheets

We will want to use CSS to style our web pages so rather than code directly in CSS we will use the SASS framework. We therefore need a pre-processor that will compile from SASS to CSS whenever we make changes. Compass is a great tool that accomplishes this feat.
Compass uses Ruby so we use the gem install process to install it:
sudo gem install compass

We now need to go and make some changes to our settings.py file. You will find this in the helloworld/helloworld folder. The one below the manage.py file.
Settings.py
This file does as it’s name suggests. It is used to store variables and configuration data used in the application.
Let’s work our way though it.
First we want to add in some data collection that enables some auto configuration:

import os
import sys
import tempfile

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
APPS_DIR = os.path.join(BASE_DIR, ‘apps’)
sys.path.insert(0, APPS_DIR)

Change ADMINS = to add your name and email contact information.
We want to use the BASE_DIR setting to help us define the absolute path for the database. Therefore we add this line in front of the DATABASES section:

DBPATH = os.path.join(BASE_DIR, ‘db/db.db’)

We will be using sqlite3 so we need to change the database information accordingly:

DATABASES = {
    ‘default’: {
        ‘ENGINE’: ‘django.db.backends.sqlite3’, # Add ‘postgresql_psycopg2’, ‘mysql’, ‘sqlite3’ or ‘oracle’.
        ‘NAME’: DBPATH,                  # 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.
    }
}

To set our Time Zone we need to look up our local time zone here: http://en.wikipedia.org/wiki/List_of_tz_zones_by_name

Update the STATIC_ROOT setting:

STATIC_ROOT = os.path.join(BASE_DIR, ‘static’)

Add a MAIN_STATIC_ROOT setting:

MAIN_STATIC_ROOT = os.path.join(BASE_DIR, ‘mainstatic’)

Add the following line to the STATICFILES_DIRS setting:

MAIN_STATIC_ROOT,

In our case we want the Eastern Time Zone. So we will use New York:

TIME_ZONE = ‘America/New_York’

Add this line to the TEMPLATE_DIRS setting:

    os.path.join(BASE_DIR, ‘templates’),

COMPASS configuration in settings.py

We need to make the following additions and changes to settings.py in order for compass to operate:

Then add the following lines:

COMPASS_INPUT = MAIN_STATIC_ROOT + ‘/sass’
COMPASS_OUTPUT = MAIN_STATIC_ROOT + ‘/stylesheets’
COMPASS_STYLE = ‘compact’
COMPASS_REQUIRES = (
    ‘ninesixty’,  # 960.gs Grid System
    )

Let’s Get Compass running… 

compass version

this will confirm that Compass is installed.

next run:

compass create ./mainstatic

This will create the SASS and stylesheet files for the project.
The compass configuration file is config.rb in the mainstatic folder.
When you want to use the CSS stylesheets add the following to your template files:

<head>
  <link href=”{{ STATIC_URL }}/stylesheets/screen.css” media=”screen, projection” rel=”stylesheet” type=”text/css” />
  <link href=”{{ STATIC_URL }}/stylesheets/print.css” media=”print” rel=”stylesheet” type=”text/css” />
  <!–[if IE]>
      <link href=”{{ STATIC_URL }}/stylesheets/ie.css” media=”screen, projection” rel=”stylesheet” type=”text/css” />
  <![endif]–>
</head>

You can configure Compass to watch for changes to your SASS files. To do this:

– Open a new terminal window
– cd to the mainstatic sub-folder
compass watch

You should see this message:

>>> Compass is polling for changes. Press Ctrl-C to Stop.

You can now minimize this window. When SASS files change the CSS files will be automatically updated.

In part 3 we will look at getting the basic home page working and then look at how we can install Twitter’s Bootstrap CSS framework and apply some styling to the home page.

 

My Journey in Python & Django: Hello World

I have been developing with Python/Django for a little while now. In most cases I have helped build something that has already been started. Recently I took part in another Health 2.0 Developer Challenge to build LessBadd.com (aka BMoreGood.com). There were some lessons from that intense weekend process. Things like this:

– Getting Python running in a shared server environment
– Particularly when you want to run Mongo alongside your application
– Integrating an easy to use stylesheet platform for CSS
– Integrating SMS and a Web front end with a common RESTful API backend.

This led me to take a step back and consider what I need for a basic “Hello World” Django app. What I want to build is a basic framework that is ready for adaptation for future projects.

For self contained Python/Django projects the configuration should be able to run in an Apache shared hosting environment but for any solution that requires additional capabilities such as Mongo then running in an Amazon EC2 instance is the way to go.

So what base configuration do I want?

Here is my thinking:

– Python/Django with sqlite3 database
– SASS pre-processor for CSS
– Compass to handle automatic compilation of CSS stylesheet changes. This only needs to be installed locally and the changes uploaded to GitHub or the target server.
– Bootstrap a CSS toolkit developed by Twitter for basic web site design

Inside the basic Hello World App I want to set up:

– An Apps folder to store different modules
– A db folder for the database files
– A Mainstatic folder to store static images and stylesheets etc.
– A Templates folder to store the HTML templates for the application.
– A Config folder where the application requirements file will be stored together with standard setup instructions.

This is the starting point. I plan to upload the basic Hello World configuration to Github so it can be used as a starting point for other applications. 

I plan on documenting the process in a series of blog posts. I have found Python and Django to be a powerful combination for rapid application development. However, integrating code from around the web can be frustrating. Making sure you have all the dependent modules in place can be a challenge. I therefore intend to document the creation of this Hello World application as completely as I can. I am sure there will be some challenges along the way, but by sharing the lessons learned I hope it can make it easier for others that are stepping along this learning curve.

There are some functional elements I want to address such as:

– Using Virtual Environments in Python via VirtualEnv to isolate each Python environment 
– Incorporating Social Network authentication and login to a User Profile configuration.
– Using the Bootstrap CSS toolkit that is responsive to various screen sizes and therefore runs well on Smartphones and Tablets

The first step is to isolate each Python Environment. To do this we will use VirtualEnv. This allows us to insulate each application from other development apps. This allows different versions of python and different additional modules to be configured – without the risk of “cross contamination” and unexpected interactions between applications.

Another early challenge is implementing Bootstrap from Twitter. The CSS Framework is getting quite a it of attention but it seems to have been originally developed to work with Ruby on Rails and the LESS pre-processor. 

So watch out for future posts that attempt to document this effort. I hope you find it useful.

Thanks to everyone who took part in a lively #HITsm tweet chat this lunchtime – Next stop HealthCa.mp/Boston #hcBos on 9/14/12

Here is the #HITSm transcript

( http://hashtags.symplur.com/healthcare-hashtag-transcript.php?hashtag=HITsm&fdate=06-22-2012&shour=09&smin=00&tdate=06-22-2012&thour=10&tmin=15&ssec=00&tsec=00&img=1 )

If you enjoyed this then check out http://healthca.mp/calendar

Join us in: 
– Boston on Friday 9/14/2012 for HealthCa.mp/Boston at the Microsoft New England Research and Development Campus.
– Kansas City on Saturday 9/22/2012 – more details to follow
– San Francisco on Friday 10/5/2012 for HealthCa.mp/SFBay at Kaiser Permanente’s world renowned Innovation Center in San Leandro.

We are looking for sponsors who want to support these great events. Our last event in Washington DC (HealthCa.mp/DC) generated more than 3.1 million Tweet Impressions  Be part of one of the liveliest Health Related People Mashup events!

My first #HITsm TweetChat! Empowering Health Care Engagement

Yesterday Twitter was “all of quiver” going down for more than an hour in the first major outage for more than six months. I don’t think that the prospect of me hosting my first #HITsm tweetchat was the reason, but you never know! (smile)

Hopefully the twitter gods will be kind and Twitter will calmly tweet along between Noon and 1pm Eastern time today.

The questions have been posted – check out the HL7 Standards blog.

Here are the topics:

#HITsm T1: Patient Engagement in health — How do we recognize and measure it?

#HITsm T2: How do we break through health’s glass wall to bring wellness sensor data in to Docs’ offices without overwhelming them?

#HITsm T3: How can we use #HITsm to give clarity to a patient’s aspirational health goal in order to guide treatment plans?

#HITsm T4: How can we use consumer wellness devices + #HITsm to engage the general population in their health?

I will be watching the #HITsm Tweetchat.

So come along and join in the conversation. I am not sure what insights I will be providing but I am fascinated to see how folks share their wisdom based on the four topics. I tried to cover a number of different aspects of Patient/Consumer Engagement:

– From the Quantitative perspective
– From the Provider perspective
– From the Patient Perspective 
– From the Population Health Perspective. 

Hopefully a little for everyone!

See you at Noon EST!

Personal Ad: If you need help on a HealthCare project where the web, mobile and social media are colliding together. Drop me an email and let’s talk! Mark AT ekivemark DOT com.