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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.