Wednesday, January 8, 2014

form label missing in Django 1.6?

You may used the monkey patch to add attrs during the form rendering.

e.g. add attribute "class" for all form labels, as this article said.
http://ask.make-money-article.com/que/2028404
def add_control_label(f):
    def control_label_tag(self, contents=None, attrs=None):
        if attrs is None: attrs = {}
        attrs['class'] = 'control-label'
        return f(self, contents, attrs)
    return control_label_tag

BoundField.label_tag = add_control_label(BoundField.label_tag)
If you had used this "solution" in your application, you may find the field names(control labels) are missed in admin site since Django 1.6, a form without label.



This is because the function .label_tag you hooked had been changed! Now, it receives an additional parameter label_suffix

Django 1.5
https://github.com/django/django/blob/1.5.5/django/forms/forms.py#L498
def label_tag(self, contents=None, attrs=None):
Django 1.6
https://github.com/django/django/blob/1.6/django/forms/forms.py#L515
def label_tag(self, contents=None, attrs=None, label_suffix=None):
So, you have to either add label_suffix in control_label_tag or use variable arguments like following slice.
def add_control_label(f):
    def control_label_tag(self, contents=None, attrs=None, *args, **kwargs):
        if attrs is None: attrs = {}
        attrs['class'] = 'control-label'
        return f(self, contents, attrs, *args, **kwargs)
    return control_label_tag

BoundField.label_tag = add_control_label(BoundField.label_tag)

No comments:

Post a Comment