Login

Decouple 'help_text' attribute from field definition

Author:
kmike
Posted:
August 30, 2010
Language:
Python
Version:
1.2
Tags:
models help_text
Score:
9 (after 9 ratings)

I found model definitions with large number of fields with long help_text unreadable and feel that help_text doesn't really belong to field definition. With this snippet help_text attributes can live outside field definitions in inner HelpText class so field definitions become shorter and more readable.

Usage:

from django.db import models
import readable_models

class MyModel(models.Model):
    __metaclass__ = readable_models.ModelBase

    name = models.CharField('Name', max_length=30)
    address = models.CharField('Address', max_length=255)
    # ... long list of fields

    class HelpText:
        name =  'The name ...'
        address = 'Example: <very verbose example is here>'
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# readable_models.py

from django.db.models.base import ModelBase as DjangoModelBase

class ModelBase(DjangoModelBase):
    ''' Decouples 'help_text' attribute from field definition. '''
    def __new__(cls, name, bases, attrs):
        help_text = attrs.pop('HelpText', None)
        new_cls = super(ModelBase, cls).__new__(cls, name, bases, attrs)
        if help_text:
            for field in new_cls._meta.fields:
                field.help_text = getattr(help_text, field.name, field.help_text)
        return new_cls

More like this

  1. Modifying the fields of a third/existing model class by marinho 4 years, 2 months ago
  2. DRY Fieldsets by DrMeers 5 years, 8 months ago
  3. Bind Administration by ashcrow 6 years, 5 months ago
  4. SerializedObjectField by dominno 4 years, 12 months ago
  5. Imagefield with variations by fivethreeo 6 years, 6 months ago

Comments

Please login first before commenting.