AJAX with Django

Software installations

Database server : Postgresql

Follow the instructions here to install a Postgresql database.

Django installation


emerge django

Install the version 1 of psycopg, because django does not handle the last one :

hermes bommings-dev # more /etc/portage/package.mask
#>net-wireless/ipw2200-firmware-2.4 
>dev-python/psycopg-1.1.21

and emerge it :

emerge psycopg

First try

Create a project :

cd ~
mkdir django
cd django
django-admin.py startproject myfirstproject

Run the django http server like that :

cd ~/django/myfirstproject
python manage.py runserver

Check if everything looks good in your favorite browser at http://localhost:8000.

Create a database :

stan@hermes ~/Bommings/bommings-dev $ createdb -U postgres -W djangodb
Mot de passe : 
CREATE DATABASE
stan@hermes ~/Bommings/bommings-dev $ 

Then edit ~/django/myfirstproject/settings.py :

# Django settings for **myfirstproject** project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Stanislas', 'stanislas.guerra@gmail.com'),
)

MANAGERS = ADMINS

DATABASE_ENGINE = 'postgresql'           # 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'.
DATABASE_NAME = 'djangodb'             # Or path to database file if using sqlite3.
DATABASE_USER = 'postgres'             # Not used with sqlite3.
DATABASE_PASSWORD = 'a password'         # Not used with sqlite3.
DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.


INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
)





Let Django create the database for each application :

stan@hermes ~/django/mysite $ python manage.py syncdb
Creating table auth_message
Creating table auth_group
...

Create applications

Create a first application directory :

cd ~/django/myfirstproject
python manage.py startapp myfirstapp

Edit the /myfirstapp/view.py file to make a simple function :

# Create your views here.
 
from django.http import HttpResponse
import datetime
 
def current_datetime(request):
  now = datetime.datetime.now()
  html = "<html><body>It is now %s.</body></html>" % now
  return HttpResponse(html)
 

You have to edit setting.py and add the app path :

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'myfirstproject.myfirstapp'
)

Map the url. Edits urls.py (the dumb way, I know, we will improve that later) :

 

Use HTML templates

First we have to create a directory to store the template file :

mkdir ~/stan/django/myfirstproject/templates

And edit the setting file setting.py in the project :

...
 
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates".
    # Always use forward slashes, even on Windows.
    '/home/stan/django/myfirstproject/templates',
)
 
...
 

A dynamic approach is to do like that :

 
TEMPLATE_DIRS = (
    os.path.join(os.path.basename(__file__), 'templates'),
)
 

Create a little template in this folder, current_datetime.html, just for as a test :

<html>
  <body>
  It is now {{ current_date }}.
  </body>
</html>
 

Now in views.py, you ca invoke the template loader :

 
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime
 
def current_datetime(request):
    now = datetime.datetime.now()
    t = get_template('current_datetime.html')
    html = t.render(Context({'current_date': now}))
    return HttpResponse(html)
 

Inheritance

Here our current_datetime.html inheriting from base.html :

{% extends "base.html" %}
 
{% block title %}The current time{% endblock %}
 
{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}
 

Where base.html contains :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h1>My helpful timestamp site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site.</p>
    {% endblock %}
</body>
</html>
 
 

Add a css

Development

Do not use this method in production !

Create a directory for medias (do not call it media, it will fails !) :


cd ~/django/myfirstproject
mkdir medias
cd medias
mkdir css

Edit the urls.py file :

from django.conf.urls.defaults import *
 
urlpatterns = patterns('',
    (r'^myfirstapp/$', 'myfirstproject.myfirstapp.views.current_datetime'),
    (r'^medias/(?P<path>.*)$', 'django.views.static.serve', \
        {'document_root': '/home/stan/django/myfirstproject/medias','show_indexes': True}),
    #Uncomment this for admin:
    (r'^admin/', include('django.contrib.admin.urls')),
)
 

Create a simple css file in the directory, basestyle.css :

 
body {
    font: 100% verdana, arial, sans-serif;
    background-color: #fff;
    margin: 50px;
}
 

And now, in our html template we can add the css like that :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
  <link rel="stylesheet" type="text/css" href="/medias/css/basestyle.css"/>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h1>My helpful timestamp site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site.</p>
    {% endblock %}
 
 
    
</body>
</html>
 

Play with the database : The MTV (MVC) concept

We have created a database as explained in the postgres page. Now we have to tell to Django the db configuration :

DATABASE_ENGINE = 'postgresql_psycopg2'           # 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'.
DATABASE_NAME = 'myfirstprojectdb'             # Or path to database file if using sqlite3.
DATABASE_USER = 'postgres'             # Not used with sqlite3.
DATABASE_PASSWORD = 'hihihi'         # Not used with sqlite3.
DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.
 
 
 
 

Ressources

 
gnu/django_en.txt · Dernière modification: 2007/04/06 16:46 par 83.204.67.66
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki