Posts Tagged ‘open source’

Developing Reusable Django Apps

Wednesday, January 13th, 2010

Django app structure is an implementation of seperation of concerns. It is slightly different than what you can find in other MVC frameworks. The stack is split vertically, not horizontally. And then the app is split horizontally within, i.e. models, views, templates etc are in their seperate modules/packages/directories. This vertical splitting allows you to collect all ingredients of one functionality in your project in one place.

Framework Structure

I think apps1 are one of the strong points of Django. A selling point if you like. There is a great ecosystem of apps, you can find an app for almost anything posssible with Python. And Python is kick-ass when it comes to library wealth. But there is another major advantage of apps when they’re done right; a sane code base. Here is a slide from the Django in the Real World presentation by Jacob Kaplan-Moss:

The fivefold path

  • Do one thing, and do it well.
  • Don’t be afraid of multiple apps.
  • Write for flexibility.
  • Build to distribute.
  • Extend carefully.

I will focus on flexibility and interoperability of apps in this post. But before we proceed I would like to emphasize the first bullet point in the slide. Because the scope of your app plays a big role in its flexibility and interoperability. Apps should be small enough to easily understand and integrate (into a project). Many times I have moved away from an otherwise good app because of its many dependencies and/or excessive features. On the other hand apps should be big enough to allow for different configurations and allow extension without modifying their code. Do one thing, and do it well.

Scope of an app

Take django-tagging for example; it’s 1.3 KLOC but it does tagging and nothing else. There are no dependencies other than Django, you can add tags to any model without modifying the model source, a tag can be associated with any type of model and tagging hides the gory details from you… In short; finding the right size is important. This is why tagging is the tagging app for Django.

Building For Reuse

General advice is “even project specific apps should be reusable“. Slapping the same app onto another project is not the only advantage. In fact it may not be possible if you are not in the habit of upgrading your whole project to recent versions of Django. The main advantage as I have said before is sanity. I prefer Django to other web frameworks/environments because it provides a civilized way of development. Let’s accept it; web programming is not a particularly interesting, exciting or intellectually rewarding field. You write the same piece of code over and over. And worst of all the challanges you face are actually a result of either the underlying system was designed by morons or you are trying to use it for something it’s not intended to be used. So it is only natural that web programmers feel they’re rusting. Django eases the pain. If you stick to certain conventions serenity will follow as well.

Naturally the framework does most of the work regarding app flexibility and interoperability. Take URLs for instance include('myapp.urls') and you are good to go. You don’t have to bind views one by one. Is it inflexible? Who said urls.py can only contain a hardcoded list of URLs. You can do anything that is possible with Python. You can generate different urlpatterns based on a setting for instance.

It is relatively easy and straightforward to reuse and extend forms and views (both function based and class based). Models are a little harder to get right though. You should always think of the most difficult situation which is you can’t touch either app’s code. Registration pattern of admin app provides a good solution here. You can register a third party model to another third party app in just a few lines.

You don’t need to write lots of code to get the flexibility and interoperability. Well designed apps make good use of settings.py for example. Why should the project developer wrap a view when a single line assignment would do the job? Supplying good templatetags and template snipplets (includes) is another way to make things easy for app consumers.

Signals provide a great way to propagate the events generated from your app. Even though they are one way2, signals are extremely powerful. Any number of observers can connect to a signal and you can send a signal anywhere in your code. Literally. It is even possible your app suppying a signal and then another app sending it3.

There are many more ways to tame your app to be reusable. It all starts with your determination and discipline. Just like documentation, testing and maintaining a software generally. I will write more about reusable apps.


1: The word application is used both for a web application and a Django application. To avoid confusion I always use app to indicate the latter.

2: Signals don’t have return values. But you can use a callback AFAIK.

3: I can’t think of an example this would be useful, but still…

Bookmark and Share

Dynamic Translation Apps for Django

Wednesday, January 6th, 2010

When I needed multi-language flatpages and flatblocks for telvee I searched for available Django apps that do dynamic translation. By dynamic translation, I mean translations are entered and stored in the database. As I said I needed to be able to translate both full pages and chunks of text that I can include into another page. I ended up rolling my own, which is without a doubt lesser to some apps below. I will try to imrove it with the good ideas from existing projects and then open source. Meanwhile I would like to share my review of 6 dynamic translation apps with you. I hope someone out there finds it useful.

Django-multilingual

One of the few active projects I have reviewed is django-multilingual. To enable a model for translations you need to create a Translation inner-class and move translatable fields inside. Then a seperate model for those fields is created behind the scenes. Django-multilingual has admin integration and a multi-language flatpages app. Another nice thing about this app is that it’s using signals internally. The API is based on getter and setter methods. For instance you call get_<fieldname>(language_id=None) on your model to get the field value for the active translation. This app has no releases and less than satisfactory API documentation and has tests only on the example project.

Django-pluggable-model-i18n

Django-pluggable-model-i18n uses registration pattern of admin app. It creates an extra model for translated fields and stores translations of non-default languages in it. This app has no releases, no tests, no API documentation and it is clearly stated to be experimental. I would also like to note the last commit date is May 25, 2009.

Django-modeltranslation

Another app that implements registration pattern is django-modeltranslation. The advantage of registration pattern is you don’t have to modify the code of the 3rd party apps you want to translate dynamically. But the database schema still needs to be modified if you are using django-modeltranslation. Also there is one translations.py for the project. I think one translation definition file per app would be better (just like admin does). Django-modeltranslation has intuitive underscore-language_code API but it is somewhat inconsistent; when you read the unsuffixed field you read the currently active language, when you write you write the default language specified in settings.py. Also the modified model stores some redundant data. For instance if your DEFAULT_LANGUAGE is "ES" both <fieldname> and <fieldname>_es columns will store the same value. Django-modeltranslation has admin integration and a management command to update database schema. Most importantly this app is the only one which has both tests and a release. (Unfortunately tests require specific settings to run)

Transdb

Transdb takes a completely different approach to dynamic translation problem. It provides two new field types; TransCharField and TransTextField. Then it serializes all your translations within a single column for each field of those. This means no JOINs and no extra queries. Unfortunately transdb doesn’t implement underscore-language_code API, you need to use get_in_language() and set_in_language() methods. Transdb has default widgets that render one form field for each language. Last commit date is Nov 07, 2008 and there is a release.

Django-multilingual-model

This one is not actually an app but just one module with 33 42 lines of code. You need to define the model that holds translations manually. This introduces some code redundancy, since you also define which fields get translated in the original model. Django-multilingual-model doesn’t implement any translation API, so it’s rather verbose to do anything with it. There are no tests and no releases. I simply don’t recommend django-multilingual-model for anything serious.

Django-transmeta

Django-transmeta stores translations in extra columns it creates in the original field’s table similar to django-modeltranslation. But you enable translation assigning a metaclass for your model and then add a Meta attribute; this means you can’t make models in existing apps translatable without modifying their code. Django-transmeta implements underscore-language_code API, has admin integration and a management command to sync database when you add new languages or translatable fields. There are documentation and code examples but no tests or releases. Last commit date it Nov 24, 2009.

Comparison of Dynamic Translation Apps

Comparison of Dynamic Translation Apps

Software development is making choices. Would you rather have a clean and stable schema with an extra translations model or avoid extra JOINs and denormalize translations onto your original model’s table? Both have advantages and disadvantages. But some choices are not based on trade-offs. Documentation, examples, tests and releases for instance. Also in my opinion underscore-language_code API is way better than any of the alternatives.

Django platform is a very powerful and intuitive one. Many people have moved in last year. This popularity affected app ecosystem as well. But unfortunately a significant number of those apps are half baked fire-and-forget type. I wish 2010 to be the year of a significant increase in software quality of Django apps. I’ll try to do my part.

Bookmark and Share

django-renderformplain

Sunday, July 26th, 2009

django-renderformplain is a Django app that allows you to render forms in plain text. I have found myself implementing quite a bit of styling into my forms and thought why do it once more when I want to render just the data. Renderformplain works both with bound forms (renders bound data) and unbound forms (renders initial data). The project is new, so there is no release yet1. But I’d like you to try it out and tell me what you think about it. And maybe find a few bugs.

An Example

After you copy renderformplain folder somewhere within your PYTHONPATH, add "renderformplain" to your INSTALLED_APPS setting to be able to run the example.

Let’s say you have a model File:

   1 class File(models.Model):
   2     name = models.CharField(max_length=100)
   3     path = models.CharField(max_length=250)
   4     size = models.IntegerField()
   5     last_modified = models.DateTimeField(default=datetime.datetime.now)
   6     created = models.DateTimeField(default=datetime.datetime.now)
   7     permissions = models.IntegerField()

And a form FileForm:

   1 class FileForm(forms.ModelForm):
   2     class Meta:
   3         model = File

Now assume you are using django.contrib.formtools.preview.FormPreview to review entered data before saving. In your formtools/preview.html template, instead of rendering the form as an HTML form, you can render it in plain text like this:

{% load renderformplain_tags %}

{% plainform form as plain_form %}

<h1>Preview your submission</h1>
{{ plain_form.as_table }}

<form action="" method="post">
  {{ form.as_hidden }}
  <input type="hidden" name="{{ stage_field }}" value="2" />
  <input type="hidden" name="{{ hash_field }}" value="{{ hash_value }}" />
  <p><input type="submit" value="Submit" /></p>
</form>

This will render the plain_form just like a normal form, except all fields will be replaced with read-only plain text.

Anyway. Try renderformplain and tell me what you think.


1: I will tag releases. Check out the repository for tags.

Bookmark and Share

django-formfieldset

Thursday, May 28th, 2009

django-formfieldset is a Django application that allows you define and render your forms with fieldsets. Just like in admin. To enable fieldset rendering you need to add FieldsetMixin as a parent class to your form and define a fieldsets attribute:

from django import forms
from formfieldset.forms import FieldsetMixin


class MyForm(forms.Form, FieldsetMixin):
    # Fields etc...

    fieldsets = ((u'Fieldset Title',
                  {'fields': ('foo', 'bar', 'baz'),
                   'description': u'This is the description for fieldset.'}),
                 (None,
                  {'fields': ('some_field',),
                   'description': u'This fieldset has no title.'}),
                 (u'Fieldset With No Description',
                  {'fields': ('some_other_field',)}))

Then you can render your form with fieldset enabled methods:

<form method="POST" action=""><table>{{ form.as_fieldset_table }}</table></form>

It is far from complete1, but feel free to download and play with it.


1: Not released yet.

Bookmark and Share

Nominate Qooxdoo for SourceForge Community Choice Awards

Saturday, May 16th, 2009

I’ve just voted Qooxdoo for Most Likely to Change the Way You Do Everything category.

You can use the link below to vote yourself:

Bookmark and Share