Login

Decouple 'help_text' attribute from field definition

Author:
kmike
Posted:
August 30, 2010
Language:
Python
Version:
1.2
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. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 3 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.