This is the fourth of a series of articles about my experience learning Pinax. In the previous articles I created a new option in the menu for a paste bin application and linked it to a very basic view.
My next step is to create a form for pasting text. I plan to do that using a form based on a model object. So the first thing I did was to write that model.
$ gedit apps/oxybeles/models.py
from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext_lazy as _ from uuid import uuid4 class PastedItem(models.Model): """ An item that was pasted. """ uuid = models.CharField(_('identifier'), max_length=36, unique=True) text = models.TextField(_('text')) in_response_to = models.ForeignKey('self', related_name='responses', blank=True, null=True, verbose_name=_('in response to')) user = models.ForeignKey(User, related_name="pasted_items", verbose_name=_('user')) pasted_at = models.DateTimeField(_('pasted at'), auto_now_add=True) def __unicode__(self): return self.uuid def save(self): if not self.uuid: self.uuid = str(uuid4()) # random so it can't be easily guessed super(PastedItem, self).save()
The uuid will be used later to refer to an object in a URL. It will be a random unique identifier. The text field is what the user pasted, and is the main content of this object.
I plan to allow responses to pasted items, so that two users can share different versions of the same text. The in_response_to field will be used for that.
Since now the application has a model object, I must tell Django about it:
$ gedit settings.py
Insert the application name inside the INSTALLED_APPS list:
INSTALLED_APPS = ( ... 'oxybeles', ... )
Then I was ready to review if the table would be created correctly:
$ python manage.py sqlall oxybeles
BEGIN; CREATE TABLE "oxybeles_pasteditem" ( "id" integer NOT NULL PRIMARY KEY, "uuid" varchar(36) NOT NULL UNIQUE, "text" text NOT NULL, "in_response_to_id" integer NULL, "user_id" integer NOT NULL REFERENCES "auth_user" ("id"), "pasted_at" datetime NOT NULL ) ; CREATE INDEX "oxybeles_pasteditem_in_response_to_id" ON "oxybeles_pasteditem" ("in_response_to_id"); CREATE INDEX "oxybeles_pasteditem_user_id" ON "oxybeles_pasteditem" ("user_id"); COMMIT;
Finally, I updated the database structure:
$ python manage.py syncdb
To test this model, I defined an administrative interface:
$ gedit apps/oxybeles/admin.py
from django.contrib import admin from oxybeles.models import PastedItem class PastedItemAdmin(admin.ModelAdmin): list_display = ('uuid', 'user', 'pasted_at',) fields = ('text', 'in_response_to', 'user',) admin.site.register(PastedItem, PastedItemAdmin)
Starting the server again and browsing to http://127.0.0.1:8000/admin/oxybeles/pasteditem/, I was able to create a few pasted items to verify that all is working:
In the next step I will create the user interface to paste new items and to view stored items.
The source code is hosted on GitHub.