The django extension

There are a lot of people trying to integrate CouchDB in their Django application. Most of the implementations are very complicated. So I decided to release the code of couchdbkit extension for Django 1.0x.

This extension provides you a threadsafe access and management of documents and views in your django application with some useful tools specific to Django.

Setup the extension

Add to your settings the `COUCHDB_DATABASES` that defines relations between your django applications and couchdb databases :

 COUCHDB_DATABASES = (
     ('djangoapp.greeting’, 'http://127.0.0.1:5984/greeting’),
 )

This defines the db greeting on url `http://127.0.0.1:5984/greeting`
for the application `greeting` of djangoapp project.

Then add the extension to your INSTALLED_APPS before any other application using
couchdbkit documents.

 INSTALLED_APPS = (
     ....
     'couchdbkit.ext.django’,
     'djangoapp.greeting’,
     ....
 )

Create a document object

A document is a simple Python object that maps properties of a Couchdb Document. Documents should be defined like Django models in the file models.py of your application:

 from couchdbkit.ext.django.schema import *

class Greeting(Document): author = StringProperty() content = StringProperty(required=True) date = DateTimeProperty(default=datetime.utcnow)

The database will be automatically set for each `Document` defined in models.py

Create your django views

First we define a `DocumentForm` instance. A `DocumentForm` works like the ModelForm object but for couchdb documents. It allows you to create form based on a Document class or instance.

 class GreetingForm(DocumentForm):    
     class Meta:
         document = Greeting

Then define your views with proper actions :

 def home(request):
    greet = None
    if request.POST:
    form = GreetingForm(request.POST)
    if form.is_valid():
        greet = form.save()  
    else:
        form = GreetingForm()

greetings = Greeting.view(“greeting/all”) return render(“home.html”, { “form”: form, “greet”: greet, “greetings”: greetings }, context_instance=RequestContext(request)

Define the Couchdb `design doc` for the application

Views/shows/lists are created in _design folder of your application :

 greeting/_design
 greeting/_design/views
 greeting/_design/views/all
 greeting/_design/views/all/map.js

To create databases and sync views, just run the usual `syncdb` command.
It won’t destroy your datas, just synchronize views.

One more thing

Obviously there are times when you need to do more than fetching document or views results. At any time you could use the database session associated to an application :

 from couchdbkit.ext.django.loading import get_db
 db = get_db('greeting’)

To go further

You could find the source of this tutorial in examples/djangoapp . If you want to go further don’t hesitate to read API .