Blog of Jeff A blog about programming and random other things.

13Oct/08link

Beginning to Code

Okay, now we're ready to start writing code! In normal Django development, you want to plan out what data your database will contain, this is important. This is due to one current flaw in Django: that Django lacks a schema evolution system. Django can only reset or create tables, but not modify existing ones.

Once you've planned out your data structures for your database, you can start creating models. Models describe how your data is stored in the database and any extra metadata your application needs to be aware of but the underlying database system may or may not be storing.

For this tutorial, I've already have a set of models designed (with some consideration for features not implemented in this tutorial series). We're going to have 4 model objects:

  • Room: this contains room information, such as name, owner, etc.
  • Message: this contains the actually message a user sends.
  • Membership: this model associates a Room with a User (aka, we know that user can view this chat room)
  • Attachment: this contains file upload information that may be associated to a particular message.

Model definitions are fairly easy to make. Let's make the Room model:

from django.db import models
import datetime
class Room(models.Model):
     name = models.CharField(max_length=200)
     created_at = models.DateTimeField('created at', default=datetime.datetime.now)
     def __unicode__(self):
         return u'%s' % self.name

Most of the code is simple. The first two lines imports the Django Model class that Django provides (which makes model definitions extremely simple) and we import the native python datetime module for, you guessed it, time functionality.

In the Room class definition we simply define properties to that tells Django what type of data each property stores. These properties are mapped as fields in the database.

For example, the name property we set stores a string (char or varchar in database terms) with a max length of 200 characters. The other two properties are just as readable. The first parameter for nearly all Field functions is a human-readable name of the field. In the case for the name property, Django will just use the field name. Also, the __unicode__ method provides a display-friendly output of a particular model (which we're outputting the room name). The friendly names are for Django's automatic admin.

  • Share/Bookmark
14Sep/08link

(Really) Getting Started

Do to some wordpress bug, there's no "Click here to continue reading" link.
In part 1 and part 2, we installed Django and installed. Now we really begin (well, the configuring part at least).

 

Settings

Depending on the purpose of your website, you need to configure different settings to make django aware of these differences such as features you want enabled, debugging mode, timezone, etc. Luckily, there are usually very little in terms of configuration.

Open settings.py for editing. The variable names and comments in this file makes most of the settings self-explanatory, so I'll briefly explain the settings we're going to edit.

 

  • DATABASE_ENGINE As stated earlier, I inted on using SQLite, so I put 'sqlite3' here. Enter your own database engine and other database information preceding it.
  • TIME_ZONE I don't know about you, but I don't happen to live in Chicago. You'll have to see the list of various time zone choices. I've entered America/New Yorkfor this, but you'll have to change this when deploy django to the server's timezone.
  • TEMPLATE_DIRS contains a list/array/tuple of strings that specify the directories that Django should look in for template files. It should be in absolute path, but if you prefer to enter the relative paths, type in the following code on the top of thesettings.py file:
import os
rel = lambda *x: os.path.join(os.path.abspath(os.path.dirname(__filename__)), *x)
Now in your TEMPLATE_DIRS variable enter something like this to include a template directory.
TEMPLATE_DIRS = (
     rel('templates'),
)
  • INSTALLED_APPS contains a list of applications that this project utilizes. Applications range from vvarious features such as user authentication to your website.

We're also planning to take advantage of Django's automatic administrative interface. So add the bolded code to your INSTALLED_APPS.

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

While we're at it, we can name our application we're about to create. I'm simply going ot name the application chat. To add it to your INSTALLED_APPS variable, put the project name period and the application name. My folder name is dchat and the application name as chat. So my INSTALLED_APPS should finally look like this:

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

Save and close your configuration file. Now back to the terminal/command line. We want to create the application using this:

python manage.py startapp chat

Which will generate a few things for us (yay).

URLs

Next thing we're going to touch upon are urls. Urls are associated by regular expressions to view code. In Django, URLs are considered an important part of your website as your content. Memorizable and readable URLs assist end users in their navigation.

In urls.py, uncomment all the comments that refer to the django automatic admin interface so your urls.py should look something like this:

from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/(.*)', admin.site.root),
)

The url patterns variable stores the way django should dispatch incoming urls. Django will automatically strip out the domain information (eg - mydomain.com) and compares the resource location with this list of regular expressions in order until it finds a match.

Each line in the patterns function call is a tuple that first contains the regular expression to match. If that expression matches, it is tied to a particular view function to call. In the case with the one above, any urls that are prefixed with admin/ are directed to admin.site.root (or the automatic admin interface). The r in front of the regular expression strip makes the string "raw", mean you cannot escape any characters. This is particularly useful for regular expressions so you don't have to escape all your slashes.

In addition to the project urls.py, you each application can have it's own urls.py. We're simply going to make a reference that tells that all urls that match none of the above patterns (aka, the automatic admin url pattern), we'll redirect it to our chat application. So add the line below the admin regular expression link:

(r'^', include('dchat.chat.urls')),

This will match any other urls in this application and redirect it to the chat/urls.py url pattern list. The advantage of doing this is to make our chat application more modularized. So we can change the base path of the chat app here, and the chat app will still function exactly the same.

Of course if you tried to view the index page (or admin url for that matter), you'd probably get something like this:

Oh no! A django error!

We simply create url.py in the chat subfolder that is identical to the url.py for the project and if we reload the page, we get a Page not found. This won't be a problem in the next tutorial, where we start adding functionality to our chat :)

 

To be continued...

  • Share/Bookmark
8Sep/08link

Getting Started

We contine with part 2 of our chat application. Part 1 we setup and installed Django.

Creating Your (Amazing) Project

Once you've downloaded and installed Django, we can now create a new Django project! Find a nice and safe location to create your project. Then we'll use the django-admin.py script provided by Django to create a new project for us using the following command:

django-admin.py startproject dchat

You can replace the dchat with whatever you want to call the project, in my case I called it dchat and use dchat in code, you should be sure to change dchat to whatever you named your project. But you can see the files that Django created for us! :)

I just really wanted to put a picture :)

And if you go into your directory via command line or terminal, you can run:

python manage.py runserver

And then access your newly created Django site via http://127.0.0.1:8000/ to see your amazing project!

  • Share/Bookmark

Recent Posts

Topics

Archives

Following

Links