Showing posts with label development. Show all posts
Showing posts with label development. Show all posts

Wednesday, July 04, 2012

My journey of discovery in Python/Django - Less is More: Part 7

In earlier posts (Part 1 herePart 2 herePart 3 herePart 4 herePart 5 here and Part 6 here) I have set about building a "Hello World" Python/Django application.
In this post I want to look at an alternative base configuration. I call this HelloLessWorld. The situation is this: 
Bootstrap is a CSS framework developed by the folks at Twitter. It is increasingly popular and is a great responsive design that can get you quickly up and running with a decent looking site. Bootstrap is becoming so popular that there are an increasing number of themes appearing. Check out BootSwatch.com for a selection of themes. We are even seeing Wordpress themes being built with bootstrap - like this WordPressBootStrap theme from 320Press. 
In the original HelloWorld project I had implemented SASS and Compass. However, Bootstrap uses LESS. Check out LessCSS.org for more background on LESS which is an alternative dynamic stylesheet language that is similar to SASS - Syntactically Awesome Stylesheets.
LESS by default uses client-side javascript to do on demand compilation of LESS stylesheets. However, you can pre-complie locally, or on the server using node.js
In order to avoid having to convert bootstrap themes to SASS from LESS I am going to take a fork of HelloWorld and replace SASS with LESS and then apply an alternative bootstrap theme.
Let's get started...
I am going to follow the process I detailed in Part 6 in order to create a new github repository and import the HelloWorld repository in to it as my starting point.
  • First I created a new empty repository on github - hellolessworld
  • Switch back to my Mac and create a new folder and a virtualenv: hlw
  • Activate the hlw environment and install django
  • git clone git@github.com:ekivemark/helloworld.git hellolessworld
  • git commit -a
  • Next I remove the .css files from base.html
  • And clean up the mainstatic folder

  • Add the reference to the less javascript in base.html

    • <link rel="stylesheet/less" type="text/css" href="{{ STATIC_URL }}bootstrap/less/bootstrap.less">
    The next step is to pick a new bootstrap theme. I went to BootSwatch and picked the Cerulean themehttp://bootswatch.com/cerulean/
    I downloaded two files to mainstatic/less:
    • variables.less
    • bootswatch.less
    Then edited the base.html to call the theme files. To do this I created a new file in mainstatic/less:
    • bootswatch-theme.less
    • I added a series of @import statements:
    • @import "../bootstrap/less/bootstrap.less";
    • @import "variables.less";
    • @import "bootswatch.less";
    • @import "../bootstrap/less/utilities.less";
    My footer styling had disappeared so to reset it I go to the original helloworld and grab the base-page.sass file. I edit the file changing the name to base-page.less and switching the variables from $ prefixed to @prefixed.  Then I add the file to the @import list in bootswatch-theme.less
    I reload the page and  the new design is in place with a modified footer.
    Hello_less_world
    Time to commit this to github. We have a modofied Bootstrap theme working with client side compilation of the LESS files.

    Tuesday, July 03, 2012

    My journey of discovery in Python/Django - Time to take the Fork in the road - but is LESS More? Part 6

    In earlier posts (Part 1 herePart 2 herePart 3 herePart 4 here and Part 5 here) I have set about building a "Hello World" Python/Django application.

    While the app itself does nothing it does have Compass and Twitter's Bootstrap framework enabled and I was able to successfully modify the framework. After uploading this to github it seems sensible to leave the app alone. So the next step is to create a fork of the code. Amazingly github makes it easier to "fork" someone else's code than to fork your own code. However, it is possible. So let's work through that process.

    The first step is to create somewhere locally to store the code. We need to clone the github repository in to  a new folder.

    Here is my process:

    • Go to my PyCharm Project directory
    • Go to the virtualenv sub-folder

    virtualenv --no-site-packages {folder short name}

    I use a short name for my new folder to avoid the confusion of multiple levels of folder with the same name. It also keeps the command prompt shorter when virtualenv is on since the folder name is used as the name for the virtualenv.

    cd {folder short name}
    source bin/activate

    To perform the cloning and forking with Git I am using the instructions from Ryan Pobasco - Fork Your Own Project on GitHub.

    Go to github and create a new project.

    on my local machine I clone the helloworld application:

    git clone git@github.com:ekivemark/helloworld.git {new application name}

    This creates a new folder and copies in the content from the helloworld application. Next I change directory in to the new folder to edit the .git/config file.

    Change the remote "origin" lines url reference to point to the new git repository instead of the original helloworld.git.

    To keep a link with the original helloworld application we can issue an "upstream" command 

    git remote add upstream git@github.com:ekivemark/helloworld.git

    Because on github I had created a README.md and .gitignore files I found I had a conflict when I tried to merge the cloned helloworld app with the new app on github.

    A quick git commit -a fixed that:

    git commit -a
    git push -u origin master

    I also moved to the parent directory and installed django

    pip install django

    Let's test everything works:

    cd {new application folder}
    mkdir db
    python manage.py syncdb
    python manage.py runserver

    I make some quick tweaks to index.html and the topnav.html files and we have a modified application

    Load the browser and go to localhost:8000. Everything appears to be working. We have a successfully cloned application.

    I wanted to apply a different color scheme to this application. Rather than develop something from scratch I went to bootswatch.com and downloaded a theme. The problem with this is that bootswatch themes are built for LESS and not SASS. So I need to edit the files so they will compile in SASS via Compass. When you are not a CSS ninja this can be a little daunting. As with many things 95% of the transition is straightforward. The transition from LESS to SCSS involved changing variable prefixes from @ to $. However, the compilation is stumbling on one particular line of converted code:

    .navbar-inner {
    #gradient > .vertical-three-colors($navbarBackground, $navbarBackground, 90%, $navbarBackgroundHighlight);
    }

    generating this error:

     Syntax error: Invalid CSS after "...al-three-colors": expected "{", was "($navbarBackgro..."
            on line 21 of ..../mainstatic/sass/partials/bootswatch-cerulean.scss
            from line 15 of ..../mainstatic/sass/screen.scss

    This challenge has drawn me in to the LESS versus SASS debate. As far as I can tell the differences between LESS and SASS are:

    • Less is closer to standard CSS
    • You can take CSS and Lessify it. This seems to be an advantage in migrating from a SASS. I can take the working CSS and reverse engineer it.
    • LESS has client-side javascript to compile the .less files to CSS.
    • There are server side compilers and even command line tools. I might even look at CodeKit for the Mac which can work with SASS and LESS.
    • Twitter's Bootstrap is built on LESS.

    I think it is time for a HelloLessWorld fork where we replace SASS with LESS.

    Posted via email from ekivemark: pre-blogspot

    My journey in Python/Django - Hello World Part 5: Bootstrap and Compass for CSS

    In earlier posts (Part 1 herePart 2 here and Part 3 here and Part 4 here) I have set about building a "Hello World" Python/Django application.
    So far we have a basic application up and running using a virtual environment, the Django template system and everything has been posted to Github. 
    Now let's get a little more sophisticated.  In this post I want to get Compass and SASS working with Twitter's Bootstrap UI tool. Bootstrap  is a combination of HTML, CSS and Javascript to create an easy to use User Interface for web projects. The initial challenge is that Bootstrap was designed using the LESS pre-processor and we want to use the SASS/Compass combination. Fortunately there have already been conversions performed that have ported Bootstrap from LESS to SASS.
    Twitter uses Ruby and we are using Django. Consequently Bootstrap makes use of Ruby and the GEM install process. Fortunately, with Compass and SASS pre-compiling code we don't need to add the complication of running a combined Ruby on Rails and Django/Python server configuration. We can contain the Ruby requirements to our local development machines and just upload the compiled code.
    Let's get started. In Part 2 we had installed Compass and setup the directory structures.
    The Javascript, CSS and Image collateral will be stored in the mainstatic folder structure:
    mainstatic
     img
     js
    sass
     stylesheets
    To implement bootstrap I am using the compass-twitter-bootstrap code from Vincent Waller. Step 1 is to install using gem:

    sudo gem install compass_twitter_bootstrap

    I then went and added:

    require 'compass_twitter_bootstrap'
    to the config.rb file in mainstatic folder. This is used by compass to control the compilation and other processes.
    I then added: 
    @import "compass_twitter_bootstrap";
    @import "compass_twitter_bootstrap_responsive";
    to the screen.scss file in mainstatic/sass.
    I then ran the following command:
    compass frameworks
    The result shows that bootstrap is installed:
    Available Frameworks & Patterns:
      * blueprint
        - blueprint/basic      - A basic blueprint install that mimics the actual blueprint css.
        - blueprint/buttons    - Button Plugin
        - blueprint/link_icons - Icons for common types of links
        - blueprint/project    - The blueprint framework.
        - blueprint/semantic   - The blueprint framework for use with semantic markup.
      * compass
        - compass/ellipsis     - Plugin for cross-browser ellipsis truncated text.
        - compass/extension    - Generate a compass extension.
        - compass/pie          - Integration with http://css3pie.com/
        - compass/project      - The default project layout.
      * twitter_bootstrap
    If we want to use all the stylistic goodness of SASS and Bootstrap the first thing we need to do is to make sure that the stylesheets and javascript files are being loaded by the application. To do this we need to edit the base template - base.html. We need to add the necessary instructions to the <head></head> section of the template.  
        <link rel="stylesheet" href="{{ STATIC_URL }}stylesheets/ie.css">
        <link rel="stylesheet" href="{{ STATIC_URL }}stylesheets/screen.css" media="screen, projection" type="text/css">
        <link rel="stylesheet" href="{{ STATIC_URL }}stylesheets/print.css" media="print" />
    The template Tag {{STATIC_URL}} is translated from the value in settings.py thanks to the following entries in the TEMPLATE_CONTEXT_PROCESSORS section of settings.py:
        "django.core.context_processors.static",
        "django.core.context_processors.request",
    Setting up Compass to watch for stylesheet changes
    Now I go to the shell and open up another window.
    I navigate to the mainstatic folder and kick off compass to watch for changes to the SCSS/JS/IMG folders. If it detects a change the code gets recompiled automatically.
    compass watch
    Let's create a NavBar that uses the bootstrap styling:
    We do this by updating include/top-nav.html:
    <div class="navbar navbar-fixed-top">
        <div class="navbar-inner">
            <div class="container">
                <ul class="nav">
                    <li class="active">
                        Hello World
                    </li>
                    <li>About</li>
                    <li>Portfolio</li>
                    <li>Contact</li>
                </ul>
            </div>
        </div>
    </div>
    A quick reload of the page and localhost:8000 now has a flashy black NavBar.
    Welcome_to_my_world-2
    We have Bootstrap working!
    The next step is to prove that we can edit the Bootstrap configuration. We want to do this without directly hacking the Compass_Twitter_Bootstrap setup. 
    The first step is to create a partials folder inside the sass folder.
    mkdir partials
    Rather than edit the original files I take a copy of a couple files from the gem setup and put them in the partials folder. In my installation the gem files were found in:
    /Library/Ruby/Gems/1.8/Gems/compass_twitter_bootstrap-2.0.3/stylesheets/compass_twitter_bootstrap/
    The files were:
    _variables.scss
    _navbar.scss
    For clarity I rename these files to use a _bootstrao prefix and add them to the import settings in screen.scss:
    /*
      revise bootstrap design using snippets in partials
    */
    @import "partials/_bootstrap-variables.scss";
    @import "partials/_bootstrap-navbar.scss";
    To prove this is working I want to go in and make some edits to the navbar setup.
    I make a couple of changes to the navbar settings to apply $orange as the background color. Compass is set to watch for changes to the scss files and it recompiles the stylesheets. A quick reload and we have a modified navbar:
    Welcome_to_my_world-4
    I also did some further editing. I created a partials/_base-page.scss file.
    In this file I created some basic CSS styling that can be used in conjunction with the base.hmtl template.
    The main new element is the footer. Here I have applied some dark grey background color with white text.
     The base.html file looks like this:
    <!doctype html>
    <html class="no-js" lang="en">
    <head>
        <title>{% block pretitle %}{% endblock %}{% block title %}Hello World! {% endblock %}{% block posttitle %}{% endblock %}</title>
        <link rel="stylesheet" href="{{ STATIC_URL }}stylesheets/ie.css">
        <link rel="stylesheet" href="{{ STATIC_URL }}stylesheets/screen.css" media="screen, projection" type="text/css">
        <link rel="stylesheet" href="{{ STATIC_URL }}stylesheets/print.css" media="print" />
        <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 class="container-fluid">
            <div class="content">
                <div class="wrapper">
                    <div class="proper-content">
                        <div class="row">
                            <div class="span12">
                                {% include "include/messages.html" %}
                                {%block featureBox %}
                                {% endblock %}
                                {%block extra_body %}
                                {% endblock %}
                            </div>
                        </div>
                    </div><!-- /.proper-content -->
                    <div class="push"></div>
                </div><!-- /.wrapper -->
                {% include "include/footer.html" %}
            </div><!-- /.content -->
        </div><!-- /.container-fluid -->
    </body>
    </html>
    The _base-page.scss file looks like this:
    /*
    base_page: Objective is a sticky header and footer
    based on:

    
    
    html, body, .container, .content {
        height: 100%;
    }
    .container, .content {
        position: relative;
    }
    .proper-content {
        padding-top: 40px; /* >= navbar height */
    }
    .wrapper {
        min-height: 100%;
        height: auto !important;
        height: 100%;
        margin: 0 auto -50px; /* same as the footer */
    }
    .push {
        height: 50px; /* same as the footer */
    }
    .footer-wrapper {
        position: relative;
        height: 50px;
    }
    */
    $footerHeight: 60px;
    html, body, .container, .content {
      height:100%;
    }
    .container, .content {
      position: relative;
      padding-left: 0px;
    }
    .proper-content {
      padding-top: $footerHeight; /* >= navbar height */
    }
    .wrapper  {
      //overflow:auto;
      min-height: 100%;
      height: auto !important;
      height: 100%;
      padding-left: 0;
      border-left: 0;
      margin: 0 auto ($footerHeight * -1); /* same as the footer but a negative value*/
    }
    .push {
      height: $footerHeight; /* same as the footer */
    }
    .footer-wrapper {
      border-left: 0px solid $grayDarker;
      position: relative;
      height: $footerHeight;
      width: 100%;
      margin-left: 0;
      padding-left: 0;
      color: $white;
      background-color: $grayDark;
    }
    One of the neat features of SASS is the ability to do math in your styling. I found that to apply some of the footer styling I needed to specify the height of the footer in pixels in a number of places. Rather than having to edit the value in multiple places I created a variable that I placed at the top of the _base-page.scss file. I define it like this:
    $footerHeight: 60px;
    In the wrapper section I needed to refer to the margin as equal to the negative value of footer height. I didn't need to create a new variable or set a static value. Instead I used arithmetic:
    margin: 0 auto ($footerHeight * -1); /* same as the footer but a negative value*/
    That is an amazingly powerful and useful feature! I am no expert when it comes to CSS but I can see the power of SASS in creating stylish websites using easily maintainable code.
    Let's commit these changes to git
    First I update .gitignore to exclude the mainstatic/.sass-cache folder
    Here is the sequence of git commands I have learned to use to keep things in sync:
    git add mainstatic/partials 
    I use JetBrains PyCharm IDE so it prompts me to add new files and folders to git as they are created. You may have to add these manually using git add.
    git status
    I use this to do a quick check of what has changed locally and see if I need to add or exclude any files.
    git checkout master
    git pull
    git checkout -b mark
    I use my name but you can use any reference you like.
    At this point you would now make the changes you need to make to the code. After that we move on to the commit phase:
    git commit -a
    At this point you need to enter a commit message that describes the changes you have implemented.
    git checkout master
    git pull
    git checkout mark
    git rebase master
    run any tests you want at this point eg. Unittests.
    git checkout master
    git merge mark
    git push
    If I am going to start another round of changes I start the git update sequence as follows:
    git branch -d mark
    Delete the branch
    git checkout master
    git pull
    git checkout -b mark
    Pull the latest version of the code and checkout my working branch - mark.
    Recap
    Let's recap where we are. 
    • We have created a folder structure for stylesheets and javascript. 
    • We have compass watching for stylesheet changes and recompiling the code
    • We have edited our template file to reference the new stylesheets
    • We have integrated Twitter's Bootstrap in to the SASS/Compass configuration 
    • We have applied some overrides to the Bootstrap design using snippets of code in our partials folder
    • We have used SASS variables and even accomplished arithmetic on the variables.
    • Checked the code in to Git

    Saturday, June 30, 2012

    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.

    Posted via email from ekivemark: pre-blogspot

    Friday, June 29, 2012

    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.

    Posted via email from ekivemark: pre-blogspot

    Wednesday, June 27, 2012

    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:
    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:
     
     
     
    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.