Login

Modify properties on fields inherited from an abstract superclass

Author:
andybak
Posted:
June 29, 2014
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

See http://stackoverflow.com/questions/927729/how-to-override-the-verbose-name-of-a-superclass-model-field-in-django/24475838#24475838

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def modify_fields(**kwargs):
    """
    Allows you to modify certain properties on fields inherited from an abstract superclass
    Usage:
    @modify_fields(timestamp={
        'verbose_name': 'Available From',
        'help_text': 'Earliest date you can book this'})
    class Purchase(BaseOrderItem):
        pass
    """
    def wrap(cls):
        for field, prop_dict in kwargs.items():
            for prop, val in prop_dict.items():
                setattr(cls._meta.get_field(field), prop, val)
        return cls
    return wrap

More like this

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

Comments

ffsffd (on June 4, 2015):

Neat approach, but this doesn't appear to work on django 1.7+ anymore - attrs on initialized fields seem to have been made readonly and you end up with AttributeError: can't set attribute

#

int_ua (on February 13, 2017):

ffsffd, was the super class abstract? It just worked perfectly for me on 1.8

#

Please login first before commenting.