Ext JS - Learning Center

Tutorial:Using Django Poll Tutorial with Ext

From Learn About the Ext JavaScript Library

Jump to: navigation, search
Summary: Using Django and Ext to build a simple blog with comments
Author: Ing. Ido Sebastiaan van Oostveen
Published: draft
Ext Version: 1.1
Languages: en.png English

This tutorial will you have to build a very simple blogging application with comments functions in Extjs and Django. It assumes that you have at least viewed and read the installation documentation and preferably the tutorial on the Django Documentation site.

The tutorial is written on a Unix system so please remember to adjust the path names for a Windows system.

Contents

Repository

You can download all the code of this demo from the mercurial repository. (provide tarball?)

$ hg clone http://ido.nl.eu.org/hg/extjs-django-blog

Simple Extjs blog build in Django

Disclaimer

This is in no means production ready code although it should have many holes in it, it's not build for production only to serve the purpose of this tutorial.

Django installation

You can download Django from the download page or check it out of the svn trunk. Django's policy is to keep the trunk stable and develop features that can break or be backwards incompatible in a different branch.

Many recent versions of Linux will have some version of Django bundled with there operating system. For example you can install Django on a Debian or Ubuntu system like this:

$ sudo apt-get install python-django

For manual installation download the package from the website and run the following commands:

$ cd /tmp
$ wget http://www.djangoproject.com/download/0.96/tarball/
$ cd Django-0.96
$ sudo python setup.py install

You can check a successful installation by running the following command.

$ django-admin  --version
0.96

If your shell returns something like:

$ django-admin  --version
bash: django-admin: command not found

The installation was not completed successfully. Please try again and read the installation documentation on the Django site carefully.

Please also make sure you'll have the Python bindings for sqlite3 installed, you'll need this further on in the tutorial.

P.S. Sometimes django-admin is called django-admin.py, this depends on your installation method and/or Linux distribution.

Creating your web project directories

The basis of your project will live in the web directory of your choice. Since we will not cover deployment on a production server here i will start out with a well structured web directory.

Create your project structure like this:

$ cd /var/www
$ mkdir extjs-django-blog
$ cd extjs-django-blog
$ mkdir -p htdocs/media/{js,css,images} templates db
$ cd htdocs/media/js
$ wget http://extjs.com/deploy/ext-1.1.1.zip
$ unzip -x ext-1.1.1.zip
$ rm ext-1.1.1.zip

This will create a root directory called extjs-django-blog with in it separate directories for the static documents (htdocs), Django templates and the database.

Now where ready to create our Django webapplication.

$ django-admin startproject webapp

This will create a directory called webapp which contains the basic layout for any Django site.

Configurating Django

Now we need to configure Django so it knows where all the different files can be found. Open settings.py in your favorite editor and edit the following variables:

DATABASE_ENGINE = 'sqlite3'           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '/var/www/extjs-django-blog/db/blog'             # Or path to database file if using sqlite3.
 
MEDIA_ROOT = '/var/www/extjs-django-blog/htdocs/'
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/media/adminmedia/'
 
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    '/var/www/extjs-django-blog/templates/',
)

You're now ready to run your Django webapp for the first time and see if everything works as expected. In the webapp directory run the following command, then open your browser and point to "http://localhost:8000/":

$ $ ./manage.py runserver  
Validating models...
0 errors found.
 
Django version 0.97-pre, using settings 'webapp.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Your web-browser should show the "It worked! Congratulations on your first Django-powered page." page.

Image:01_first_startup.jpg

Creating the blog

Now to create the blogging application we use:

$ ./manage.py startapp blog

This will create a directory called blog in your webapp. Before we start creating our datamodels and views for this webapp, we need to add it in settings.py to the INSTALLED_APPS list:

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

Please note that i also added django.contrib.admin to get access to the fantastic build-in django administration pages. Will use them later on to add posts to our blog.

Will now define a very simple data model that will hold our blog posts. Edit the file blog/models.py with your favorite editor like so:

from django.db import models
 
# Create your models here.
class Post(models.Model):
    slug = models.SlugField(prepopulate_from=('title',), primary_key=True)
    title = models.CharField(maxlength=50)
    date = models.DateTimeField(auto_now_add=True)
    body = models.TextField()
 
    def __str__(self):
        return self.title
 
    def get_absolute_url(self):
        return "/blog/%s/%s/" % (self.date.strftime("%d/%m/%Y").lower(), self.slug)
 
    class Admin:
        list_display = ('slug', 'title', 'date',)
        search_fields = ('title', 'body',)
        date_hierarchy = 'date'
 
    class Meta:
        get_latest_by = 'date'
        ordering = ('-date',)

For Your Information: A Slug is a term from the newpaper world and it serves as a unique named identifier so that different blog posts with the same title can be referenced by named instead of by primary key number.

We now run Django's syncdb option to create the tables from our model in the database. If this is the first time you've ran syncdb it will ask you if your want to create a superuser, answer Yes and supply a user name and password. (I've chosen user name 'test' with password 'test' for the repository)

$ ./manage.py syncdb

Everything for a basic blogging application is now done. It still doesn't have public pages and most importantly no Ext has been used yet, but we do have a fully functional blog ready in the admin pages.

Administration menu

Login to the Administration menu by pointing your browser to http://localhost:8000/admin/, you'll need to have the development server running with the "./manage.py runserver" command. You can leave this server running in another terminal and it will update itself automatically every time you modify the code.

Image:02 admin menu.jpg

For good measure add some entries to your blog by clicking the "+ Add" button right from the entry Posts. Notice that Slug is Automatically filled in when you start typing in the Title you don't need to type the title twice. Type something into the body field and press Save.

Okey now we got some data in our Blogging Application, we're ready to start doing some Ext. But first where going to define our URL's.

Urls

Every web application uses and needs url's. In Django you define the structure of your website by defining the url's it's using in a file called urls.py'. The syntax of this file can be pretty powerful when you use includes(), but for this tutorial i'll limit myself to just the main urls.py file in webapp/urls.py.

Every url is specified as a regular expressing so they can be very flexible, they are mapped on views which is basic python code to complete the MVC paradigm.

As this is a simple blogging application, we will not create our own views but simply use Django's build in generic views.

Add the following lines to the webapp/urls.py file:

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.views.generic.list_detail import object_list, object_detail
from webapp.blog.models import Post
 
blog_dict = {
    'queryset': Post.objects.all().order_by('-date'),
    'template_name': 'blog/post_list.html',
}
blog_detail_dict = dict(blog_dict, **{
    'slug_field': 'slug',
    'template_name': 'blog/post_detail.html',
})
 
urlpatterns = patterns('',
    # Blog frontpage
    (r'^$', direct_to_template, {'template': 'index.html'}),
    # Blog list of entries
    (r'^blog/$', object_list, blog_dict),
    # Blog entry
    (r'^blog/\d+/\d+/\d+/(?P<slug>[-\w]+)/$', object_detail, blog_detail_dict),
 
    # Uncomment this for admin:
    (r'^admin/', include('django.contrib.admin.urls')),
)

At this point we also have defined three different template files.

  • index.html
  • blog/post_list.html
  • blog/post_detail.html

This will lead us to the last step of creating the basic Django blogging application.

Templates

Every modern uses and loves there templating system. It's almost hard to remember life without them. Django support any templating system you can access from Python, but it defaults to it's own system which is both fast and easy.

Add the following template files to your template directory:

/var/www/extjs-django-blog/templates/index.html

<html>
<head></head>
<body>
<div>This will contain our ext app very soon</div>
<div>For now take a look at your blog templates: <a href="blog/">blog</a></div>
</body>
</html>

/var/www/extjs-django-blog/templates/blog/post_list.html

{% for object in object_list %}
<div class="listentry">
    <a href="{{ object.get_absolute_url }}">{{ object.title }}</a>
</div>
{% endfor %}

/var/www/extjs-django-blog/templates/post_detail.html

<div class="post">
    <div class="title">{{ object.title }}</div>
    <hr>
    <div class="body"><pre>{{ object.body }}</pre></div>
</div>

Now point your browser to http://localhost:8000/ and look at the index page, nothing fancy here :) you can click on blog and view the post you made earlier on in the admin pages.

Time to add some Ext to the mix :)

Ext Blogging App

For the basic design of the blog i copied most of Jack's FeedViewer code as it seemed the post appropriate.

General layout:

  • layout north, contains/displays our blog's name
  • layout west, contains all blog entries
  • layout center, contains the blog entry
  • layout south, contains status bar

Ext retrieves the list of all blog entries via the blog/json/ url and view we created before. This is loaded into a datastore and shown as buttons the toolbar of the westpanel.

When a user clicks on the button, the appropriate blog entry is loaded in the center panel.

Image:xx_result_second_post.jpg

Adding Comments (Using Django FreeComments)

Work in progress / todo

Deployment on a production server

This is extensively covered on the Django documentation site.

More Ext in Django

You can also put Extjs in the django admin pages, for this example the Ext htmleditor would have been very nice to have in the Post CRUD pages. However this is outside the scope of this tutorial.

Other Work

Look at my site http://ido.nl.eu.org for more ext examples (labeled extsamples) for more uses of Django and Ext. Some of the examples have the full server-side Django code as readable files, that is all i've used for those examples and shows how easy using Extjs with Django is.

Random Notes

  • Python allows the use of trailing comma's for it's datatypes. No trailing-comma-will-break-your-app in the Python world :)
  • This page was last modified on 29 October 2007, at 11:47.
  • This page has been accessed 20,036 times.